方法一
汉字markedTextRange输入超过,就不能再输入
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Get the current text
guard let text = textField.text else { return true }
// Calculate the new text length
let newLength = text.count + string.count - range.length
let value = (text as NSString).replacingCharacters(in: range, with: string).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).replacingOccurrences(of: " ", with: "")
if value.count > 25 {
return false
}
return true
}
方法二
汉字markedTextRange输入超过, 还能输入,确定的时候截取
textField.addTarget(self, action: #selector(textFieldChange(titleTF:)), for: .editingChanged)
@objc func textFieldChange(titleTF: UITextField) {
if titleTF.markedTextRange != nil {return}
guard var genString = titleTF.text else {return}
if genString.count > 100 {
let startIdx = genString.startIndex
let endIdx = genString.index(genString.startIndex, offsetBy: 100-1)
genString = String(genString[startIdx...endIdx])
}
titleTF.text = genString
}
方法三
extension MyUIViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 防止删除键无效
if string == "" {
return true
}
var tmpStr = textField.text ?? ""
if tmpStr.count >= 20 {
// 处理中文高亮
if let languageStr = UIApplication.shared.textInputMode?.primaryLanguage {
// 中文输入
if languageStr == "zh-Hans" {
// 获取高亮 Range
if let selectedRange = placeholderTF.markedTextRange {
// 高亮开始 Index
let startValue = selectedRange.start.hashValue
// 高亮结束 Index
let endValue = selectedRange.end.hashValue
// 高亮 Range
let tmpRange = NSRange(location: startValue, length: endValue - startValue)
// 如果高亮 Range 和 联想词的 Range 一致, 则用联想词替换全部高亮
if range == tmpRange {
let startIndex = tmpStr.index(tmpStr.startIndex, offsetBy: startValue)
let selectedStr = tmpStr.suffix(from: startIndex)
tmpStr = tmpStr.replacingOccurrences(of: String(selectedStr), with: string)
self.placeholderTF.text = String((tmpStr).prefix(maxNum))
}
}
}
}
return false
}
return true
}
}