0

我有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.

4

2 回答 2

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
        }

    }
于 2019-04-17T10:32:15.177 回答
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
}
于 2019-04-17T10:24:35.520 回答