Max length UITextField

后端 未结 18 1834
一个人的身影
一个人的身影 2020-11-30 17:42

When I\'ve tried How to you set the maximum number of characters that can be entered into a UITextField using swift?, I saw that if I use all 10 characters, I can\'t erase t

18条回答
  •  隐瞒了意图╮
    2020-11-30 18:14

    You can use in swift 5 or swift 4 like image look like bellow

    1. Add textField in View Controller
    2. Connect to text to ViewController
    3. add the code in view ViewController

       class ViewController: UIViewController , UITextFieldDelegate {
      
        @IBOutlet weak var txtName: UITextField!
      
        var maxLen:Int = 8;
      
       override func viewDidLoad() {
          super.viewDidLoad()
      
          txtName.delegate = self
         }
      
       func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      
           if(textField == txtName){
              let currentText = textField.text! + string
              return currentText.count <= maxLen
           }
      
           return true;
         }
      }
      

    You can download Full Source form GitHub: https://github.com/enamul95/TextFieldMaxLen

提交回复
热议问题