Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an uneditable text suffix to a UITextField

I have a UITextField that I'd like to add a "?" suffix to all text entered.

The user should not be able to remove this "?" or add text to the right hand side of it.

What's the best way to go about this?

like image 220
Glen T Avatar asked Nov 27 '11 19:11

Glen T


1 Answers

Use the UITextFieldDelegate protocol to alter the string whenever the field is being edited. Here's a quick stab at it; this will need work, but it should get you started.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * currentText = [textField text];
    if( [currentText characterAtIndex:[currentText length] - 1] != '?' ){
        NSMutableString * newText = [NSMutableString stringWithString:currentText];
        [newText replaceCharactersInRange:range withString:string];
        [newText appendString:@"?"];
        [textField setText:newText];
        // We've already made the replacement
        return NO;
    }
    // Allow the text field to handle the replacement 
    return YES;
}
like image 139
jscs Avatar answered Sep 23 '22 08:09

jscs