我有UIAlertViewController
,如下图所示。
这是我的代码:
let alertController = UIAlertController(title: alertTitle.security, message: "", preferredStyle: UIAlertController.Style.alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = placeholder.security
textField.tintColor = .black
textField.isSecureTextEntry = true
}
我想防止在UITextField
中插入一些特殊字符。
答案 0 :(得分:2)
您必须为文本字段分配委托
textField.delegate = self
然后检查是否有特殊字符
extension ViewController: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.isFirstResponder {
let validString = CharacterSet(charactersIn: "!@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")
if let range = string.rangeOfCharacter(from: validString) {
return false
}
}
return true
}
}
答案 1 :(得分:0)
希望获得帮助:
let alertController = UIAlertController(title: alertTitle.security, message: "", preferredStyle: UIAlertController.Style.alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = placeholder.security
textField.tintColor = .black
textField.isSecureTextEntry = true
textField.delegate = self // new
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "(special chracter)" {
return false
}
return true
}