Julian
Julian

Reputation: 75

UITextField make part not editable

How can I make a part of the UITextField non-editable? What I mean by this is I set a default value to the text field and I only want users to be able to edit the part that they add. Is this possible? If so, please tell me how I can go about doing this.

Upvotes: 2

Views: 872

Answers (2)

Ricardo Sanchez-Saez
Ricardo Sanchez-Saez

Reputation: 9566

@property (nonatomic) NSString *myString;    

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myString = @"whatever";
    self.myTextField.text = self.myString;
    self.myTextField.delegate = self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     // Avoid user replacing characters from myString
     if (range.location < [self.myString length])
     {
         return NO;
     }
     // Allow adding or replacing new characters after myString
     return YES;
}

Upvotes: 2

ethyreal
ethyreal

Reputation: 3669

Have a look at the UITextFieldDelegate:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // get textField.text string using range and compare it to your default.
    // return no if you don't want it to change
}

Alternatively instead of using a "default" value, consider using a placeholder value instead, this will be cleared when they type anything and if you leave it blank you could just accept the placeholder value as the default.

Upvotes: 0

Related Questions