Swift 防止“0”成为 1 个特定 uiTextField 的第一个字符

Swift prevent "0" being first character for 1 specific uiTextField

所以我在网上搜索“func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool”如何格式化文本字段。我发现这种方法可以防止“0”成为我文本字段中的第一个字符。它有效,但实际上不是我想要的方式。

问题是,在我的注册视图中有 4 个 uiTextfield,其中包含:

我只想防止“0”作为我的 PhoneNum TextField 的第一个字符。但是使用这段代码,我有点将所有这 4 个文本字段放入防止“0”作为第一个字符。

这是我的代码:

@IBOutlet weak var textFullName: SkyFloatingLabelTextField!
@IBOutlet weak var textPhoneNumber: SkyFloatingLabelTextField!
@IBOutlet weak var textPIN: SkyFloatingLabelTextField!
@IBOutlet weak var textConfirmPIN: SkyFloatingLabelTextField!


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    // I try this one
    if string == "0" {
        if textField.text!.count == 0 {
            return false
        }
    }
    
    // i also try to change the "textField" into "textPhoneNumber"
    if string == "0" {
        if textPhoneNumber.text!.count == 0 {
            return false
        }
    }
    

   // both of those method wont work
  
    return true
}

谁能告诉我如何防止我的文本Phone数字不能输入“0”作为它的第一个字符?使用这种方法,我只将我所有的文本字段放入无法键入“0”作为其第一个字符。

谢谢大家

你可以通过等式==符号直接检查textField是否为textPhoneNumber

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == textPhoneNumber {
        // do textPhoneNumber stuff
    } else {
        // others
    }
    return true
}

UITextFieldDelegate 方法将为视图控制器设置为委托的所有文本字段调用。

大概您的 textField(_:shouldChangeCharactersIn:replacementString:) 方法被所有 4 个 SkyFloatingLabelTextField 对象调用(我假设它们是 UITextField 的自定义子类。)

如果您希望不同的文本字段有不同的行为,您需要编写代码来分别处理每种情况。像这样:

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

    switch textField {
        case textPhoneNumber:
            //Special case code to handle the phone number field
            if string == "0" {
                if textField.text!.count == 0 {
                   return false
                }
                return true
            }

        case textFullName:
            //Special case code to handle the name field (if needed.)
        default:
            //Shared code to handle the other fields the same way
    }
}