ios textfield max length SWIFT 4 code example
Example: textField.characther range
ViewController: UIViewController, UITextFieldDelegate {
let myTextField : UITextField = {
let textField = UITextField()
textField.backgroundColor = .white
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
myTextField.delegate = self
setUpViews()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let curruntCharachterCount = textField.text?.count ?? 0
if range.length + range.location > curruntCharachterCount{
return false
}
let newLength = curruntCharachterCount + string.count - range.length
return newLength <= 1
}
func setUpViews() {
view.addSubview(enterPinTextField)
enterPinTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
enterPinTextField.centerXAnchor.constraint(equalTo: mainScreenView.centerXAnchor).isActive = true
enterPinTextField.widthAnchor.constraint(equalToConstant: 150).isActive = true
enterPinTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}