Restrict deletion on UITextField

70 views Asked by At

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?

2

There are 2 answers

0
Anbu.Karthik On

why you not try just like the simple method add the one more UIView in prefix of the UItextfield

enter image description here

0
Anuj Rajput On

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