美文网首页
Swift UItextField、UITextView限制字数

Swift UItextField、UITextView限制字数

作者: 路有点颠簸 | 来源:发表于2022-01-12 15:47 被阅读0次
    extension LUserInfoEditCtrl: UITextFieldDelegate,YYTextViewDelegate {
        
        //限制TF开头不能输入空格
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if string == " " {
                return false
            }
            return true
        }
        
        @objc func tfDidChange(textField: UITextField) {
            let maxLength = 10
            let toBeString : String = textField.text ?? ""
            let lang = textField.textInputMode?.primaryLanguage
            if lang == "zh-Hans" {
                //简体中文输入
    
                //获取高亮部分
                let selRange = textField.markedTextRange
                let position = textField.position(from: selRange!.start, offset: 0)
    
                //没有高亮选择的字,则对已输入的文字进行字数统计和限制
                if (position == nil) {
                    if toBeString.count > maxLength {
                        textField.text = String(toBeString.prefix(maxLength))
                    }
                }
    
            }else {
                //中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
                if toBeString.count > maxLength {
                    let aaa = toBeString as NSString
                    let rangeIndex = aaa.rangeOfComposedCharacterSequence(at: maxLength)
                    if rangeIndex.length == 1 {
                        textField.text = String(toBeString.prefix(maxLength))
                    }else {
                        let rangeRange = aaa.rangeOfComposedCharacterSequences(for: NSMakeRange(0, maxLength))
                        textField.text = aaa.substring(with: rangeRange)
                    }
                }
            }
            
            nameCountLab.text = "\(textField.text?.count ?? 0)/10"
        }
        
        
        func textViewDidChangeSelection(_ textView: YYTextView) {
            let num = textView.text.count
            let maxLength = 50
            if num > maxLength {
                textView.text = String(textView.text.prefix(maxLength))
            }
            
            infoCountLab.text = "\(num)/\(maxLength)"
        }
        
        
    }
    

    相关文章

      网友评论

          本文标题:Swift UItextField、UITextView限制字数

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