If you'd like to wait til the user is done add this:
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (textField.text.length < 4){
textField.textColor = [UIColor redColor];
}
else{
textField.textColor = [UIColor blackColor];
}
}
If you'd like to do it in real time:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
int resultantLength = textField.text.length + string.length - range.length;
NSLog(@"Length After Additions And Subtractions Will Be: %i letters", resultantLength);
if (resultantLength < 4){
textField.textColor = [UIColor redColor];
}
else{
textField.textColor = [UIColor blackColor];
}
return YES;
}
Note that this will affect any textField that uses the same delegate. If you'd like to only respond to a specific textField, for example _username
, do this:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == _username) {
int resultantLength = textField.text.length + string.length - range.length;
NSLog(@"Length After Additions And Subtractions Will Be: %i letters", resultantLength);
if (resultantLength < 4){
textField.textColor = [UIColor redColor];
}
else{
textField.textColor = [UIColor blackColor];
}
}
return YES;
}
Make sure your ViewController is set up for UITextFieldDelegate protocol and it is the delegate of your textField