首页 > 解决方案 > Swift:复制/粘贴特定字段的启用和禁用

问题描述

我已经创建了用户名并创建了密码。用户名没有字符限制,但密码有 8 位字符限制。如何仅禁用密码字段的复制/粘贴。以及如何过滤一些对用户名无效的字符。

标签: iosswiftxcode

解决方案


对于复制和粘贴问题:

您将需要创建自己的继承 UITextField 的 TextField 类,然后覆盖canPerformAction委托方法以禁用粘贴:

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    if action == "paste:" {
        return false
    }        
    return super.canPerformAction(action, withSender: sender)
}

更详细的描述:如何在 Swift 中禁用 TextField 中的粘贴?

对于人物问题:

与上面类似的概念,除了您需要实现textFieldDidEndEditingshouldChangeCharactersIn委托方法。

textFieldDidEndEditing将允许您在用户停止编辑该字段后评估该字段中的字符串。例子:

func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
    switch textField {
        case usernameTextField:
            // evaluate the `textField.text` for is a valid username
        case passwordTextField:
            // evaluate the `textField.text ` for is a valid password
    }
}

shouldChangeCharactersIn将允许您评估每次击键的字符串(我更喜欢在评估文本字段输入时使用后者)。例子:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    switch textField {
        case usernameTextField:
            // evaluate the `replacementString` for is a valid username
        case passwordTextField:
            // evaluate the `replacementString` for is a valid password
    }
    return true
}

推荐阅读