【问题标题】:How to prevent special characters in UITextField of UIAlertViewController?如何防止 UIAlertViewController 的 UITextField 出现特殊字符?
【发布时间】:2019-09-07 13:39:41
【问题描述】:

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

【问题讨论】:

标签: ios swift uitextfield uialertviewcontroller


【解决方案1】:

希望得到帮助:

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
}

【讨论】:

    【解决方案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
            }
    
        }
    

    【讨论】:

    • @UdayBabariya 什么不起作用?,也许你忘了添加textField.delegate = self
    • -UiAlertViewController 不使用其基础 ViewController 的委托方法。
    • 只有当您将UIAlertViewController 子类化时,这种情况才会发生
    • 你能在问题中添加所有相关代码吗,你到底在做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2016-02-13
    • 2019-06-21
    • 2015-06-25
    • 1970-01-01
    • 2017-05-02
    • 2015-01-01
    相关资源
    最近更新 更多