Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add label to UITextField

Tags:

iphone

In question 663830, Isaac asks about adding a button to a text field. Can someone show code to add a label to the .rightView property?

Or, is there some better way to include 'permanent' text in a text field?

This is for a calculator that would include units in the field (mg, kg, etc.) without having to maintain a label outside of the text field. Sort of like permanent placeholder text?

Thanks, Chris

like image 422
Chris Brandt Avatar asked Apr 13 '09 21:04

Chris Brandt


1 Answers

Quick and dirty code:

- (void)viewDidLoad {
    [super viewDidLoad];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];
    textField.borderStyle = UITextBorderStyleLine;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    label.text = @"mg";
    label.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.rightView = label;
    [self.view addSubview:textField];
    [label release];
    [textField release];
}

Note that I'm adding the subview from the ViewController, you can do it from the view as well.

like image 62
pgb Avatar answered Sep 22 '22 15:09

pgb