Add shortcut to UITextField

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

Or is there a better way to include “persistent” text in a text box?

This is a calculator that will include units in a field (mg, kg, etc.) without having to store the label outside the text field. How like a constant placeholder text?

Thank you, Chris

+5
source share
3 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];
}

Please note that I am adding subview from ViewController, you can do this from view too.

+9
source

leftView ( rightView) UITextField - . "" .

- (void)loadView
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text = @"To:";
label.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
self.UITextField.leftViewMode = UITextFieldViewModeAlways;
self.UITextField.leftView = label;
}
+3

I know that maybe I'm a little late for the party, but I'm sure it can help future programmers in this situation.

You can create a category to make it easier to use in several applications, such as:

UITextField + PaddingLabel.h

#import <UIKit/UIKit.h>

@interface UITextField (PaddingLabel)

-(void) setLeftPaddingText:(NSString*) paddingValue width:(CGFloat) width;

-(void) setRightPaddingText:(NSString*) paddingValue width:(CGFloat) width;

@end

UITextField + PaddingLabel.m

#import "UITextField+PaddingLabel.h"

@implementation UITextField (PaddingLabel)

-(void) setLeftPaddingText:(NSString*) paddingValue width:(CGFloat) width
{
    UILabel *paddingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, self.frame.size.height)];
    paddingLabel.text = paddingValue;
    self.leftView = paddingLabel;
    self.leftViewMode = UITextFieldViewModeAlways;
}

-(void) setRightPaddingText:(NSString*) paddingValue width:(CGFloat) width
{
    UILabel *paddingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, self.frame.size.height)];
    paddingLabel.text = paddingValue;
    self.rightView = paddingLabel;
    self.rightViewMode = UITextFieldViewModeAlways;
}

@end

Usage example:

[self.dateTextField setLeftPaddingText:@"DATE:" width:defaultWidth];
+1
source

All Articles