Restrict the number of characters in UITextField [duplicate]

北城以北 提交于 2019-12-30 11:15:30

问题


I've seen a lot of answers, but it seems that none of them has worked. I have a programmatically created UIAlertView with two UITextFields. I want to restrict the number of characters :

  • 12 characters in first field
  • 1 character in second field

First field code:

alertDialog.addTextField { (nameField) in
        nameField.placeholder = "Name"
        nameField.borderStyle = .roundedRect
        nameField.clearButtonMode = .whileEditing
        }

And second

alertDialog.addTextField { (keyField) in
        keyField.placeholder = "Key"
        keyField.borderStyle = .roundedRect
        keyField.clearButtonMode = .whileEditing

    }

How can I correctly restrict the number (Let's pretend that there will be no paste in these field)


回答1:


Set textField delegates to respective class (in my case self is ViewController)

nameField.delegate = self
keyField.delegate = self

Then you can restrict characters by

extension ViewController : UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        switch textField {
        case nameField:
            if ((textField.text?.length)! + (string.length - range.length)) > 12 {
                return false
            }

        case keyField:
            if ((textField.text?.length)! + (string.length - range.length)) > 1 {
                return false
            }
        }
        return true 
    }
}



回答2:


You can add an event like this:

textField1.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
textField2.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

Then implement this function:

func textFieldDidChange(textField: UITextField) {
    if textField == self.textField1 && textField.text.length > 12 { 
        // Do whaterver you want
    }
    if textField == self.textField2 && textField.text.length > 1 { 
        // Do whaterver you want
    }
}


来源:https://stackoverflow.com/questions/41280540/restrict-the-number-of-characters-in-uitextfield

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