Assigning Character Limit to a Specific UITextField

前端 未结 2 911
暖寄归人
暖寄归人 2021-01-26 09:24

The following code works but applies to all TextFields. How can I limit it to one specific TextField?

Code:

func textField(_ textField:          


        
2条回答
  •  暖寄归人
    2021-01-26 10:14

    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
    }
    

提交回复
热议问题