Assigning Character Limit to a Specific UITextField

前端 未结 2 910
暖寄归人
暖寄归人 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:05

    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
            }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题