UITextField转大写/小写后的光标位置到最后问题

2021-09-14  本文已影响0人  XueYongWei

本意是限制输入仅英文字母和数字,同时将字母转为大写。
测试发现了在修改的时候,每输入一个字符,光标都跑到最后,无法连续输入修改。

解决办法:

class CustomField {
// ...
addTarget(self, action: #selector(upperText), for: .editingChanged)
delegate = self
// ...
}

extension CustomField: UITextFieldDelegate {
    
    @objc private func upperText() {
        let textRange: UITextRange? = selectedTextRange
        text = text?.uppercased()
        selectedTextRange = textRange
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard !string.isEmpty else {return true}
        
        let set: CharacterSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
            .inverted
        let result: String = string.components(separatedBy: set)
            .joined(separator: "")
        var valid: Bool = result == string
        let textFieldContent: String = (textField.text ?? "")
            .appending(string)
        if valid, textFieldContent.count > 10 {
            // 字符合法,但是追加后超出长度限制
            valid = false
        }
        return valid
    }
}


上一篇下一篇

猜你喜欢

热点阅读