Reputation: 27050
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?
Upvotes: 0
Views: 57
Reputation: 844
You can simply show a non-editable UILabel
before the UITextField
where the user actually enters the number. When you get the input from the user and want to process it, prefix "+91-" before the user input string
Upvotes: 1
Reputation: 82759
why you not try just like the simple method add the one more UIView
in prefix of the UItextfield
Upvotes: 1