ios swift5 UITextView占位字符,记录限制字数

发布于:2024-10-12 ⋅ 阅读:(137) ⋅ 点赞:(0)

截图

请添加图片描述

请添加图片描述

代码:具体使用

 scrollView.addSubview(contentTextView)
        contentTextView.placeholderLabel.text = LocalizableManager.localValue("write_comment")
        contentTextView.maxCharacters = 500
        contentTextView.backgroundColor = newUIBackColor
        contentTextView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.top.equalTo(problemLabel.snp_bottomMargin).offset(20)
            make.height.equalTo(150)
        }
        contentTextView.characterCountChanged = { [self] count in
            print("当前输入了 \(count) 个字符")
            textCountLabel.text = String(count) + "/500"
        }

代码:CustomTextView

class CustomTextView: UITextView {

    // 占位文字
     var placeholderLabel: UILabel!
    
    // 最大字符数
     var maxCharacters = 200

    // 输入字符数变化的回调
    var characterCountChanged: ((Int) -> Void)?
    
    // 初始化方法
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    private func setup() {
        // 设置代理
        delegate = self
        
        //设置textView的字体大小
        self.font = UIFont.systemFont(ofSize: 15)
        
        // 创建并设置占位文字的标签
        placeholderLabel = UILabel()
        placeholderLabel.text = LocalizableManager.localValue("report_description_tips")
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.numberOfLines = 0
        placeholderLabel.isHidden = !self.text.isEmpty
        addSubview(placeholderLabel)
        updatePlaceholderFrame()
        
       
    
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        updatePlaceholderFrame()    }
    
    private func updatePlaceholderFrame() {
        let placeholderSize = placeholderLabel.sizeThatFits(CGSize(width: self.frame.width - 10, height: CGFloat.greatestFiniteMagnitude))
        placeholderLabel.frame = CGRect(x: 5, y: 5, width: placeholderSize.width, height: placeholderSize.height)
    }
}

extension CustomTextView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        // 更新占位文字的可见性
        placeholderLabel.isHidden = !textView.text.isEmpty
        
        // 限制输入的字符数
        if textView.text.count > maxCharacters {
            textView.text = String(textView.text.prefix(maxCharacters))
        }
        
        // 通知外部关于字符数的变化
        characterCountChanged?(textView.text.count)
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到