Is there a way to permanently add a letter to a UITextField where the user cannot delete it? I want to add a single character and the user not be able to delete it but they can still add letters after.
Cheers,
p.s. This is for iOS
A UITextField
has a delegate method called should change characters in range, this method basically ask, should i add or remove the next character? and from that you can dictate what you would like. Here is some example code.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
BOOL shouldChangeCharacters = ( (textField.text.length + string.length) > 1 );
return shouldChangeCharacters;
}
This code means if the new character being added plus the current text is greater than 1 then it is okay to make the change, if the text is not greater than one, then we will not make the change...
Now, under the assumption that someone may try to paste over your character, this delegate method is still called but you have to do a few things.
if (range.location == 0) {
NSString* firstCharacter = [string substringToIndex:1];
BOOL firstCharacterIsDesiredCharacter = [firstCharacter isEqualToString:@"#"];
if ( !firstCharacterIsDesiredCharacter ) {
NSString* symbolWithText = [NSString stringWithFormat:@"#%@",text];
// ******************** \\
[textView setText:symbolWithText];
return NO;
// or we could do this
string = symbolWithText;
// ******************** \\
}
}
Both scenarios, are modifying the values of the parameters... some people don't like doing that. It could be a bad programming practice.. or if you are going to modify them there's some process you should do first.
With that, we only need to run this code if they are trying to replace the first character, i substituted the hash tag symbol, the first character is from a range of location 0 and length of 1. So if the range is equal to 0, then we run our code to fix it. This code also takes into consideration that they might be pasting the special symbol with it. so if the UITextField
read #work, and they tried to copy "work" or "#work" it takes both scenarios into consideration and completely skips the code if the hash mark is the first character.
UITextField Reference
try this
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text = @"left";
label.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
textField.leftViewMode = UITextFieldViewModeAlways;
textField.leftView = label;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With