Assigning Character Limit to a Specific UITextField

断了今生、忘了曾经 提交于 2019-12-02 09:50:58

Assuming that you have two textFields and your controller is a delegate of both.

  @IBOutlet var aMagesticTextField: UITextField!
  @IBOutlet var anotherMagesticTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        aMagesticTextField.delegate = self
        anotherMagesticTextField.delegate = self
    }

In shouldChangeCharactersIn, check the textField parameter against your known text fields.

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

Two Options

1) Implement the code you referenced in the UITextFieldDelegate implementation for only that one TextField. I strongly prefer this option.

2) Conditionally check for something that uniquely identifies the TextField you are interested in such as its tag property. Only run the character count check for that TextField. Otherwise, default to true.

I never use the tag property for identifying a UI element and don't suggest it. However, I see it used often.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!