Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add % sign to UITextField programmatically

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.

like image 662
StackRunner Avatar asked Dec 11 '22 22:12

StackRunner


2 Answers

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.

like image 198
Cyrille Avatar answered Dec 14 '22 11:12

Cyrille


[NSString stringWithFormat:@"%d%%", number];
like image 35
beryllium Avatar answered Dec 14 '22 11:12

beryllium