Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a live UITextField count while typing (Swift)?

I would like to count the character when user keep typing in UITextField with swift.

Image of Field and Label:

enter image description here

I have already placed UITextField and UILabel, just haven't found any information on Stack overflow, also if you can do one in UITextView I also appreciate it.

like image 711
Brian Nezhad Avatar asked Jun 05 '15 00:06

Brian Nezhad


People also ask

How do I limit the number of characters in UITextField or UITextView?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).


2 Answers

To use the function below you need to implement the UITextFieldDelegate protocol on the text field you want to count. This gets called every time the UITextFields text changes:

Your class declaration should look something like this

class ViewController: UIViewController, UITextFieldDelegate 

You should have an @IBOutlet similar to this

@IBOutlet var txtValue: UITextField 

Set the UITextField s delegate to self.

override func viewDidLoad() {     super.viewDidLoad()     txtValue.delegate = self                 }  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {     let newLength = count(textField.text.utf16) + count(string.utf16) - range.length      mylabel.text =  String(newLength) // Set value of the label     // myCounter = newLength // Optional: Save this value     // return newLength <= 25 // Optional: Set limits on input.      return true } 

Note that this function is called on all UITextFields so if you have several UITextFields you will need to add a logic to know witch one is calling this function.

like image 138
Icaro Avatar answered Sep 18 '22 14:09

Icaro


A very elegant and neat solution exists using UITextFieldDelegate. My solution uses the concept of selectors. In a selector you tell your compiler what function/action to perform when a particular event happens. In this case - typing in textfield. Make sure that you have set the textField delegate in storyboard.

override func viewDidLoad() {    super.viewDidLoad()    yourTextField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), for: UIControlEvents.EditingChanged) }  @objc func textFieldDidChange(textField : UITextField){    label.text = yourTextField.text?.count } 
like image 45
Yash Tamakuwala Avatar answered Sep 19 '22 14:09

Yash Tamakuwala