textfield.characther Range
ViewController: UIViewController, UITextFieldDelegate {
//create textfield view constructor
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// must write this line
setUpViews()// call func for constraint
}
//func for text limit
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 // set max limit of numbers
}
func setUpViews() {
//constraint setup
view.addSubview(enterPinTextField)
//textField constraint
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
}
}