美文网首页
swift TextFight、TextView输入时的字数限制

swift TextFight、TextView输入时的字数限制

作者: 艾欧尼亚 | 来源:发表于2019-07-23 17:28 被阅读0次

TextField

1.给textField 添加监听

NotificationCenter.default.addObserver(self, selector:
            #selector(textFieldChanged), name:
            NSNotification.Name(rawValue:
                "UITextFieldTextDidChangeNotification"),
                                                      object:self.nameTextField)

2.实现监听方法

  @objc func textFieldChanged(obj:Notification) {
        let limit : Int = 4
        let textField : UITextField = obj.object as! UITextField
        //非markedText才继续往下处理
        guard let _: UITextRange = textField.markedTextRange else{
            textField.text = filtercharactor(searchText: (textField.text ?? ""), regexStr: "[^\u{4e00}-\u{9fa5}]")
            if(textField.text! as NSString).length > limit{
                MBProgressHUD.xy_hide()
                MBProgressHUD.xy_show("最多支持4个字哦")
                textField.text = (textField.text! as NSString).substring(to:limit)
            }
            return
        }
    }
限制只输入汉字
    func filtercharactor(searchText: String,regexStr: String) -> String? {
        if let regex = try? NSRegularExpression.init(pattern: regexStr, options: .caseInsensitive) {
            let resultStr = regex.stringByReplacingMatches(in: searchText, options: .reportCompletion, range: NSRange(location: 0, length: searchText.count), withTemplate: "")
            return resultStr
        }else{
            return nil
        }
    }

TextView

func textViewDidChange(_ textView: UITextView) {
        
        let limit = 100
        
        if textView.text.count > limit {
            textView.text = String(textView.text.prefix(limit))
            textView.undoManager?.removeAllActions()
            textView.becomeFirstResponder()
            return
        }
    }

相关文章

网友评论

      本文标题:swift TextFight、TextView输入时的字数限制

      本文链接:https://www.haomeiwen.com/subject/wwpalctx.html