Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Adding text to UITextField you can't delete

What I would like to do is to add some text at the beginning of UITextField that cannot be deleted. I add this text when the user taps on UITextField like this:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    if (textField.text.length == 0) {
        textField.text = @"myText";
    }

    return YES;
}

How do I prevent the user from deleting this text in a normal way? (without adding a separate UILabel on top of the TextField, for example). Thanks in advance!

Upvotes: 4

Views: 3272

Answers (3)

Nishant Tyagi
Nishant Tyagi

Reputation: 9913

Use this

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([[textField text] length]==LENGTH_OF_TEXT && [string isEqualToString:@""])
    {
        return NO;
    }
else 
return YES;
}

Hope it helps you.

Upvotes: 0

Mani
Mani

Reputation: 17585

You can implement this code in shouldChangeCharactersInRange delegate method.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length == 1 && [string isEqualToString:@""]) {//When detect backspace when have one character. 
        textField.text = @"myText";
    }
    return YES;
}

Upvotes: 3

bryanmac
bryanmac

Reputation: 39296

Checkout shouldChangeCharactersInRange in the UITextFieldProtocolReference

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

the text field calls this method whenever the user types a new character in the text field or deletes an existing character.

So, you have control on whether text actually gets changed so you can insert your custom logic in that delegate callback enforcing whatever rules about what can change.

Upvotes: 1

Related Questions