Assigning Character Limit to a Specific UITextField

ⅰ亾dé卋堺 提交于 2019-12-02 15:41:01

问题


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

Code:

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
}

回答1:


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
        }



回答2:


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
}


来源:https://stackoverflow.com/questions/41969325/assigning-character-limit-to-a-specific-uitextfield

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