I would like to know how to add a % sign to any number inserted into a UiTextfield so the user can be aware that it is a percentage similar to how $ or % signs work when setting cell types in excel.
I have looked all over stack overflow but was wondering if there was any other way than appending a % using an observer.
What you want is the rightView
property of UITextField
. Here's a little category I wrote that helps you set permanent 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 as of now.
[NSString stringWithFormat:@"%d%%", number];
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