微信、boss等應(yīng)用,輸入框只要有限制文本長(zhǎng)度,都會(huì)出現(xiàn)奔潰。
UITextField和UITextView限制字符長(zhǎng)度,輸滿輸入框后,粘貼后再撤銷奔潰。
復(fù)現(xiàn)步驟
0、粘貼板有粘貼的內(nèi)容。
1、輸入框文本輸滿。
2、該輸入框鍵盤彈起。
3、三只手指選中同時(shí)點(diǎn)擊鍵盤。
4、依次點(diǎn)擊系統(tǒng)彈出的控件粘貼和撤銷按鈕。
解決辦法:
/// 處理undo奔潰
class InputLimit: NSObject{
@objc static func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, maxInputCnt: Int) -> Bool {
return textInput(textField, shouldChangeCharactersIn: range, replacementString: string, maxInputCnt: maxInputCnt)
}
@objc static func textView(_ textView: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, maxInputCnt: Int) -> Bool {
return textInput(textView, shouldChangeCharactersIn: range, replacementString: string, maxInputCnt: maxInputCnt)
}
private static func textInput(_ textInput: UITextInput, shouldChangeCharactersIn range: NSRange, replacementString string: String, maxInputCnt: Int) -> Bool{
guard let textRange = textInput.textRange(from: textInput.beginningOfDocument, to: textInput.endOfDocument) else{return false}
let optionalText = textInput.text(in: textRange)
guard let text = optionalText else { return true }
let len = text.count + string.count - range.length
if len <= maxInputCnt {
if (string.isEmpty && range.length > 0 && text.count < range.location + range.length) {
/// 這里可以判斷為刪除或者為撤銷,
/// text.count < range.location + range.length判斷從中間刪除
let fillText = text.count > range.length ? String(text.dropLast(range.length)) : ""
textInput.replace(textRange, withText: fillText)
return false
}
return true
}
return false
}
}
這里隱藏一個(gè)很深的bug,留言區(qū)留言我告訴你。