iOS Swift UITextField限制输入最大字数 实时截断

//假设限制输入10个字

let  wordNum = 10

fileprivate lazy var textTF:UITextField = {

        let textTF = UITextField(frame: CGRect(x: 10, y: 50, width: 300, height: 50))

        textTF.addTarget(self, action: #selector(textFieldChange), for: .editingChanged)

       textTF.backgroundColor = .cyan

        return textTF

}()

@objc func textFieldChange(_ titleTF: UITextField) {

               if titleTF.markedTextRange != nil {return}

            guard var genString = titleTF.text else {return}

            if genString.count > wordNum{

                let startIdx = genString.startIndex

                let endIdx = genString.index(genString.startIndex, offsetBy: wordNum-1)

                genString =String(genString[startIdx...endIdx])

            }

            titleTF.text = genString

    }

//" 去掉首尾空格 和 尾部换行 ".trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

你可能感兴趣的:(iOS Swift UITextField限制输入最大字数 实时截断)