I am writing validation for my textfield, I found something interesting that whether I can check how many digits I am typing into the textfield at real time. My text field i
Update Swift 4.0
txtFieldAdd.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
Now call your function. In my case, this will enable the save button
@objc func textFieldDidChange(_ textField: UITextField) {
if (txtFieldAdd.text?.isEmpty)! {
btnSave.isEnabled = false
}
else {
btnSave.isEnabled = true
}
}
Hope it helps.
This is how you get realtime validation without setting up anything other than the delegate of the textfield:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Creating the future string. The incoming string can be a single character,
// empty (on delete) or many characters when the user is pasting text.
let futureString: String = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
// Determine if the change is allowed, update form, etc.
let allowChange = <#Your Validation Code#>
return allowChange
}
Add this code to the designated delegate of the textfield. Simple.
[textField addTarget:self action:@selector(checkTextField) forControlEvents:UIControlEventEditingChanged];
Try it!
Use UITextFieldDelegate. especially this function
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
and you can get sample codes links from here..
Set up a delegate for the UITextField
and implement the method – textField:shouldChangeCharactersInRange:replacementString:
Details and examples are in the UITextFieldDelegate Protocol Reference, but here's a quick example:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
NSString *text = [textField text];
// NOT BACKSPACE
if ([string length] || text.length + string.length < 8) {
return YES;
} else if (text.length + string.length > 8) {
return NO;
} else {
// DO SOMETHING FOR LENGTH == 8
return YES;
}
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
// [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
NSLog(@"%@",searchStr);
return YES;
}