swift - maximum input limit input box textview

 

 

 

Foundation Import
 / * * 
 * package the textView 
 * / 
class JYCustomerTextView: JYBaseView { 
    
    /// Show title 
    Private the lazy var titleLab: UILabel = JYUIModel.creatLabe (text: nil, font: UIFont.systemFont (ofSize: 16 ), textColor: UIColor. the init (hexstring: " # 424 242 " ))
     /// shows the maximum number of words 
    Private the lazy var maxCountLab: UILabel = JYUIModel.creatLabe (text: nil, font: UIFont.systemFont (ofSize: 12 is ), textColor: UIColor.init (hexstring: " # 9B9B9B " ))
     /// input text
    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- [the textView] [maxCountLab] -8-| " , Options: [], metrics: nil, views: VD))
         return V 
    } () 
    /// maximum character input box can be displayed 
    Private  var maxCount: Int = 100 
    ///The current number of characters entered 
    Private  var the currentCount: Int = 0 
    
    /// constructor
     /// 
    /// - the Parameters:
     ///    - title: title display
     ///    - placeholderStr: prompt text placeholder
     ///    - maxCount : man can enter up to 
    Convenience the init (title: String, placeholderStr:? String ?, maxCount: Int = 100 ) { 
        self.init () 
        self.titleLab.text = title 
        self.placeholderLab.text = placeholderStr 
        self.maxCount = maxCount 
    } 
    
    the override the init (Frame: the CGRect) { 
        the 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)" 
        } The else{ 
            Self.maxCountLab.text = " \ (100) / \ (maxCount) " 
        } 
    } 
    /// Get the text entered textView
     /// 
    /// - Returns: err present description in full text exceeds the maximum value, text input text 
    FUNC getTextViewText () -> (ERR:?? String, text: String ) {
         var inputText = self.textView.text
         var ERR: String?
         IF the let T = inputText .jy.trimAllSpace () replacingOccurrences (of:?. " \ n- " , with: " " ) .replacingOccurrences (of: " \ R & lt " ), T.isEmpty == , With: "" Privateto false {
             IF inputText? .count ?? 0 > self.maxCount { 
                ERR = " can not enter \ (maxCount) characters " 
            } 
        } the else { 
            inputText = "" 
        } 
        return (ERR, inputText) 
    } 
    
    /// set the title rich text 
    FUNC setTitleAttributText (attributeText: as NSAttributedString) { 
        self.titleLab.attributedText = attributeText 
    } 
    // monitor changes in the text input box 
    @objc FUNC textViewTextChange (notication: the 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))
    }
}

 

 

use:

    /// display shop description 
    Private the let shopInduceView = JYCustomerTextView (title: " Store Introduction " , placeholderStr: " Please enter the store information " , maxCount: 100 ) 


    /// Gets text input
     /// 
    /// - Returns: the presence err exceeds a maximum value described in full text, text input text 
    FUNC getInputText () -> (ERR:? String ?, text: String ) {
         return self.shopInduceView.getTextViewText () 
    } 

/// initial data 
self.shopInduceView.setTextViewText ( " 11111 " ) 

 /// rich text settings
self.shopInduceView.setTitleAttributText(attributeText: attributText)

 

Guess you like

Origin www.cnblogs.com/qingzZ/p/11526059.html