Swift UItextField、UITextView限制字数

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)"
    }
    
    
}

限制输入小数点后保留两位小数

func textField(_ textField:UITextField, shouldChangeCharactersIn range:NSRange, replacementString string:String) ->Bool{
        if string.length==0{
            return true
        }
        //第一个参数,被替换字符串的range
        //第二个参数,即将键入或者粘贴的string
        //返回的是改变过后的新str,即textfield的新的文本内容
        let checkStr = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
        //正则表达式(只支持两位小数)
        let regex = "^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$"
        //判断新的文本内容是否符合要求
        return self.isValid(checkStr: checkStr!, regex: regex)
    }
    //检测改变过的文本是否匹配正则表达式,如果匹配表示可以键入,否则不能键入
    func isValid(checkStr:String, regex:String) ->Bool{
        let predicte = NSPredicate(format:"SELF MATCHES %@", regex)
        return predicte.evaluate(with: checkStr)
    }

你可能感兴趣的:(Swift UItextField、UITextView限制字数)