I've a UITextField
with text like, +91-
(that's country caller code of India). Now when my user input his number into that textfield, it would look like this, +91-1234567890
that's good, now when he tap (x) delete key from keyboard, I want to restrict deletion, its only possible up to, 1
(first digit of his mobile number), at any case, he should not be able to delete +91-
. I'm able to do it with - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
delegate, like this,
1) First way:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:@""]) { //detect back space
if([textField.text hasSuffix:@"-"]) { //has suffix `-`
return NO;
}
}
}
2) Second way:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//if text length is length of caller code and detect back space
if(textField.text.length<=4 && [string isEqualToString:@""]) {
return NO;
}
return YES;
}
In both the ways, I'm getting what I want, but not sure its proper or not? Any more smoother way?
why you not try just like the simple method add the one more
UIView
in prefix of theUItextfield