本意是限制输入仅英文字母和数字,同时将字母转为大写。
测试发现了在修改的时候,每输入一个字符,光标都跑到最后,无法连续输入修改。
解决办法:
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
}
}
网友评论