Limit characters in TextField or TextView Swift - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

13 Nov 2017

Limit characters in TextField or TextView Swift

In this article we will learn how to set maximum character length to a UITextField and UITextView.

We go through each one separately.

UITextField:

First add UITextField to the view and conform to UITextFieldDelegate.

Next add the following delegate method for setting up the maximum limit:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
    return updatedText.count <= 10 // Change limit based on your requirement.
} 

Above example is for, if user asked to enter his/her mobile number, assume maximum length as 10.

Download the sample project from the bottom of this article.

UITextView:

Add UITextView to the view and conform to UITextViewDelegate.

Next add the following delegate method for setting the maximum limit:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let currentText = textView.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: text)
    return updatedText.count <= 50 // Change limit based on your requirement.
}

Above example is for, if user asked to enter about his/her, assume maximum limit here 50 characters.

Download sample project with example :

No comments:

Post a Comment

Post Top Ad