Add% sign to UITextField programmatically

I would like to know how to add the% sign to any number inserted in the UiText field so that the user can know that this is a percentage similar to the way the $ or% signs work when setting cell types in excel.

I looked at the stack overflow, but wondered if there is any other way than adding% using an observer.

+4
source share
3 answers

What you need is the rightView UITextField property. Here is a small category I wrote that helps you set constant prefixes or suffixes to text fields:

 @implementation UITextField (Additions) - (void)setPrefixText:(NSString *)prefix { UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; [label setBackgroundColor:[UIColor clearColor]]; [label setFont:[UIFont fontWithName:self.font.fontName size:self.font.pointSize]]; [label setTextColor:self.textColor]; [label setAlpha:.5]; [label setText:prefix]; CGSize prefixSize = [prefix sizeWithFont:label.font]; label.frame = CGRectMake(0, 0, prefixSize.width, self.frame.size.height); [self setLeftView:label]; [self setLeftViewMode:UITextFieldViewModeAlways]; [label release]; } - (void)setSuffixText:(NSString *)suffix { UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; [label setBackgroundColor:[UIColor clearColor]]; [label setFont:[UIFont fontWithName:self.font.fontName size:self.font.pointSize]]; [label setTextColor:self.textColor]; [label setAlpha:.5]; [label setText:suffix]; CGSize suffixSize = [suffix sizeWithFont:label.font]; label.frame = CGRectMake(0, 0, suffixSize.width, self.frame.size.height); [self setRightView:label]; [self setRightViewMode:UITextFieldViewModeAlways]; [label release]; } @end 

By the way: https://stackoverflow.com/search?q=uitextfield+rightview : 4,099 results at the moment.

+9
source
 [NSString stringWithFormat:@"%d%%", number]; 
+3
source

Use the UITextFieldDelegate textFieldDidEndEditing: method.

Example:

 - (void)textFieldDidEndEditing:(UITextField *)textField { NSString *oldText = textField.text; textField.text = [NSString stringWithFormat:@"%@ %%",oldText]; } 
0
source

Source: https://habr.com/ru/post/1432329/


All Articles