4

I'm using a UILabel as the leftView of a UITextField. The issue is that the textField's text is higher than the label's.

This is the code I've used so far

UILabel *startsWith = [[UILabel alloc] init];
startsWith.font = [UIFont systemFontOfSize:14];
startsWith.textColor = [UIColor blackColor];
startsWith.backgroundColor = [UIColor clearColor];
startsWith.text = @"Text";
[startsWith sizeToFit];
self.textField.leftViewMode = UITextFieldViewModeAlways;
self.textField.leftView = startsWith;

I've tried slightly changing the label's frame but it didn't work...

How can I align both texts?

Moxy
  • 4,162
  • 2
  • 30
  • 49
  • 1
    You could try subclassing `UITextField` and then overriding `- (CGRect)leftViewRectForBounds:` – sooper Jul 04 '12 at 17:18

1 Answers1

7

You could create a container view in which you position the UILabel 1px up.

    UIView * v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];

    UILabel *startsWith = [[UILabel alloc] init];
    startsWith.font = self.textfield.font;
    startsWith.textAlignment = self.textfield.textAlignment;
    startsWith.textColor = [UIColor blackColor];
    startsWith.backgroundColor = [UIColor clearColor];
    startsWith.text = @"Text";
    [startsWith sizeToFit];

    startsWith.frame = CGRectOffset(startsWith.frame, 0, -1);
    v.frame = startsWith.frame;
    [v addSubview:startsWith];
    self.textfield.leftViewMode = UITextFieldViewModeAlways;
    self.textfield.leftView = v;
Templar
  • 1,694
  • 1
  • 14
  • 32
  • It works perfectly! Thank you! Is there a way to reduce the horizontal space between the label and the text input? – Moxy Jul 04 '12 at 19:48
  • 1
    You're welcome. Maybe you can reduce it by reducing the leftview's width, in this case v's frame, I can't test it rigth now. If you need more special functioning, maybe the subclassing and method overriding is the best approach. Look [HERE](http://stackoverflow.com/questions/2694411/text-inset-for-uitextfield). – Templar Jul 04 '12 at 19:55
  • reducing the left view's width made it! Thanks again!! – Moxy Jul 04 '12 at 20:07
  • Nice. Don't even bother customizing leftVew with auto layout constraint. It's a hell of a pain in the ass :) – midnight Apr 29 '21 at 09:28