swift - 有最大输入限制的输入框textview

 

swift - 有最大输入限制的输入框textview_第1张图片

 

 

import Foundation
/**
 *  封装textView
 */
class JYCustomerTextView: JYBaseView {
    
    /// 显示标题
    private lazy var titleLab: UILabel = JYUIModel.creatLabe(text: nil, font: UIFont.systemFont(ofSize: 16), textColor: UIColor.init(hexString: "#424242"))
    /// 显示最大字数
    private lazy var maxCountLab: UILabel = JYUIModel.creatLabe(text: nil, font: UIFont.systemFont(ofSize: 12), textColor: UIColor.init(hexString: "#9B9B9B"))
    /// 输入文本
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.translatesAutoresizingMaskIntoConstraints = false
        tv.delegate = self
        tv.backgroundColor = UIColor.init(hexString: "FFF7EF")
        tv.font = UIFont.systemFont(ofSize: 14)
        tv.textColor = UIColor.init(hexString: "#4a4a4a")
        tv.returnKeyType = .done
        tv.addSubview(self.placeholderLab)
        let vd: [String: UIView] = ["placeholderLab": placeholderLab]
        tv.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-4-[placeholderLab]", options: [], metrics: nil, views: vd))
        tv.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[placeholderLab]", options: [], metrics: nil, views: vd))
        return tv
    }()
    /// 提示文字Lab
    private lazy var placeholderLab: UILabel = JYUIModel.creatLabe(text: nil, font: UIFont.systemFont(ofSize: 14), textColor: UIColor.init(hexString: "#9b9b9b"))
    
    /// 占位背景View
    private lazy var placeBgView: UIView = {
        let v = JYUIModel.createView(bgColor: UIColor.init(hexString: "#FFF7EF"))
        v.layer.cornerRadius = 6
        v.layer.masksToBounds = true
        v.addSubview(self.textView)
        v.addSubview(self.maxCountLab)
        let vd: [String: UIView] = ["textView": textView, "maxCountLab": maxCountLab ]
        v.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-6-[textView]-6-|", options: [], metrics: nil, views: vd))
        v.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[maxCountLab]-6-|", options: [], metrics: nil, views: vd))
        v.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[textView][maxCountLab]-8-|", options: [], metrics: nil, views: vd))
        return v
    }()
    /// 输入框能显示的最大文字
    private var maxCount: Int = 100
    /// 当前已输入的文字数
    private var currentCount: Int = 0
    
    /// 构造器
    ///
    /// - Parameters:
    ///   - title: 显示的标题
    ///   - placeholderStr: 占位提示文字
    ///   - maxCount: 能输入的最多汉子
    convenience init(title: String? , placeholderStr: String?, maxCount: Int = 100) {
        self.init()
        self.titleLab.text = title
        self.placeholderLab.text = placeholderStr
        self.maxCount = maxCount
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.configUI()
        NotificationCenter.default.addObserver(self, selector: #selector(textViewTextChange(notication:)), name: UITextView.textDidChangeNotification, object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: nil)
        DDLOG(message: "deinit JYCustomerTextView")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - logic API
extension JYCustomerTextView{
    
    /// 设置输入内容
    ///
    /// - Parameter text: 内容
    func setTextViewText(_ text: String)  {
        self.placeholderLab.isHidden = !text.isEmpty
        self.textView.text = text
        currentCount = textView.text.count
        if currentCount <= maxCount {
            self.maxCountLab.text = "\(currentCount)/\(maxCount)"
        }else{
            self.maxCountLab.text = "\(100)/\(maxCount)"
        }
    }
    /// 获取textView输入的文字
    ///
    /// - Returns: 存在err说明如数文字超过最大值,text输入的文字
    func getTextViewText() -> (err: String? , text: String?) {
        var inputtext = self.textView.text
        var err: String?
        if let t = inputtext?.jy.trimAllSpace().replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: ""),t.isEmpty == false {
            if inputtext?.count ?? 0 > self.maxCount {
                err = "最多只能输入\(maxCount)个汉字"
            }
        }else{
            inputtext = ""
        }
        return (err , inputtext)
    }
    
    /// 设置title的富文本
    func setTitleAttributText(attributeText:NSAttributedString) {
        self.titleLab.attributedText = attributeText
    }
    // 监听输入框文本变化
    @objc private func textViewTextChange(notication: Notification) {
        self.placeholderLab.isHidden = !self.textView.text.isEmpty
    }
}

// MARK: - UITextViewDelegate
extension JYCustomerTextView: UITextViewDelegate{
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n"{
            // 点击完成
            textView.resignFirstResponder()
            return false
        }
        if currentCount >= maxCount,text != "" {
            return false
        }
        return true
    }
    func textViewDidChange(_ textView: UITextView) {
        if textView.markedTextRange == nil || textView.markedTextRange?.isEmpty == true {
            currentCount = textView.text.count
            if currentCount <= maxCount {
                self.maxCountLab.text = "\(currentCount)/\(maxCount)"
            }else{
                textView.text = String(textView.text.prefix(100))
                self.maxCountLab.text = "\(100)/\(maxCount)"
            }
        }
    }
}

// MARK: - UI API
extension JYCustomerTextView{
    /// 布局界面
    private func configUI() {
        self.tintColor = UIColor.init(hexString: "#FD914B")
        self.addSubview(placeBgView)
        self.addSubview(titleLab)
        let vd: [String: UIView] = ["titleLab": titleLab , "placeBgView": placeBgView]
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-14-[titleLab]-14-|", options: [.alignAllCenterY], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-13-[placeBgView]-13-|", options: [], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[titleLab]-15-[placeBgView(133)]|", options: [], metrics: nil, views: vd))
    }
}

 

 

使用:

    /// 显示店铺介绍
    private let shopInduceView = JYCustomerTextView(title: "店铺介绍", placeholderStr: "请输入店铺信息", maxCount: 100)


    /// 获取输入的文字
    ///
    /// - Returns: 存在err说明如数文字超过最大值,text输入的文字
    func getInputText() -> (err: String?, text: String?) {
        return self.shopInduceView.getTextViewText()
    }

///初始数据
self.shopInduceView.setTextViewText("11111")

 /// 设置的富文本
self.shopInduceView.setTitleAttributText(attributeText: attributText)

 

你可能感兴趣的:(swift - 有最大输入限制的输入框textview)