Josue Espinosa
Josue Espinosa

Reputation: 5089

Label inside UITextField

In my application, i'm trying to create UITextFields that looks like this:

| Name:      John Doe       |
| Email:     [email protected] |
| Number:    (123)456-7890  |

Name is a left view label that will never be editable, there is a small constant left padding on the labels, and a right padding on the label so the placeholder text/ actual text in the textfield all begin at the same place.

I tried giving them all a constant width, then padding the label from the left, but then the label text appeared all the way to the left with no padding there, like this:

|Name:      John Doe       |
|Email:     [email protected] |
|Number:    (123)456-7890  |

Now, the way i'm trying to implement it, is as follows:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 70, 40)];
label.text = @"Name:";
label.font = [label.font fontWithSize:20];
label.textAlignment = NSTextAlignmentRight;
self.testTextField.layer.borderColor=[[UIColor lightGrayColor]CGColor];
self.testTextField.layer.borderWidth= 1.0f;
label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
self.testTextField.leftViewMode = UITextFieldViewModeAlways;
self.testTextField.leftView = label;

The textfield was made with IB, and it looks like it should, except:

The text/placeholder needs padding from the left view label. It appears to be right next to it, but needs to be padded. How can I add this padding?

Upvotes: 3

Views: 1660

Answers (1)

Josue Espinosa
Josue Espinosa

Reputation: 5089

Unfortunately, I resorted to creating a subclass of UITextField and changing the origin of the left view of the text field. Here is what I did:

- (CGRect) leftViewRectForBounds:(CGRect)bounds {
    CGRect textRect = [super leftViewRectForBounds:bounds];
    textRect.origin.x += 10;
    return textRect;
}

Upvotes: 3

Related Questions