Restrict the number of characters in UITextField [

2019-02-19 18:14发布

This question already has an answer here:

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)

标签: ios swift swift3
2条回答
不美不萌又怎样
2楼-- · 2019-02-19 18:38

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 
    }
}
查看更多
萌系小妹纸
3楼-- · 2019-02-19 18:39

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
    }
}
查看更多
登录 后发表回答