I would like to count the character when user keep typing in UITextField with swift.
Image of Field and Label:
This will only allow your textfield input 14 char
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "14"
self.textfield.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
if(newLength <= 14){
self.label.text = "\(14 - newLength)"
return true
}else{
return false
}
}
}
And Screenshot
