//假設(shè)限制輸入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)