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
  }
}

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source