undo奔潰的問(wèn)題

微信、boss等應(yīng)用,輸入框只要有限制文本長(zhǎng)度,都會(huì)出現(xiàn)奔潰。

UITextFieldUITextView限制字符長(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ū)留言我告訴你。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容