As an iOS developer one should know how to manipulate with text field and it’s operation, Apple has already provided UITextFieldDelegate protocol.
To read more about it https://developer.apple.com/documentation/uikit/uitextfielddelegate
You may have seen may application where forms are involved, and you see number of characters you’re entering when you type specially on the forms where characters are restricted to certain count.
In this post we’re going to see the same how to display the character count, when you type in TextField.
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TextFieldCount”
Step 2 − Open Main.storyboard and add TextField and label as shown, create @IBOutlet for label and text field and name them as lblCount, txtInputBox respectively.
Step 3 − In ViewController.swift confirm to protocol UITextFieldDelegate and the the delegate with textInputBox to self.
class ViewController: UIViewController, UITextFieldDelegate { txtInputBox.delegate = self
Step 4 − Implement the delegate shouldChangeCharactersIn and write following code inside it.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if(textField == txtInputBox){ let strLength = textField.text?.count ?? 0 let lngthToAdd = string.count let lengthCount = strLength + lngthToAdd self.lblCount.text = "\(lengthCount)" } return true }
Step 5 − Run the application, For final code,
Example
import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var txtInputBox: UITextField! @IBOutlet var lblCount: UILabel! override func viewDidLoad() { super.viewDidLoad() txtInputBox.delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if(textField == txtInputBox){ let strLength = textField.text?.count ?? 0 let lngthToAdd = string.count let lengthCount = strLength + lngthToAdd self.lblCount.text = "\(lengthCount)" } return true } }