将字符限制分配给特定的UITextField

以下代码有效,但适用于所有TextField。 如何将其限制为一个特定的TextField?

码:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentCharacterCount = (textField.text?.characters.count) ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length return newLength <= 9 } 

假设你有两个textFields,你的控制器是两者的委托。

  @IBOutlet var aMagesticTextField: UITextField! @IBOutlet var anotherMagesticTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() aMagesticTextField.delegate = self anotherMagesticTextField.delegate = self } 

在shouldChangeCharactersIn中,根据已知的文本字段检查textField参数。

  if textField == aMagesticTextField { //It's aMagesticTextField } else { //It's anotherMagesticTextField } 

两个选项

1)仅针对那一个TextField实现您在UITextFieldDelegate实现中引用的代码。 我非常喜欢这个选项。

2)有条件地检查唯一标识您感兴趣的TextField的内容,例如其tag属性。 仅运行该TextField的字符计数检查。 否则,默认为true。

我从不使用tag属性来识别UI元素,也不建议使用它。 但是,我看到它经常使用。

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Set textField tag to 9 if you want pass this guard guard textField.tag == 9 else { return true } let currentCharacterCount = (textField.text?.characters.count) ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length return newLength <= 9 }