如何防止UIAlertViewController的UITextField中的特殊字符?

时间:2019-04-17 10:19:45

标签: ios swift uitextfield uialertviewcontroller

我有UIAlertViewController,如下图所示。
enter image description here

这是我的代码:

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中插入一些特殊字符。

2 个答案:

答案 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
}
相关问题