What's the correct way to put a line under a UITextField

1.7k views Asked by At

I want to have a borderless UITextField but underneath have a 1 or 2 pixel high guide line that underlines the field. To be clear, I don't want just the text INSIDE the UITextField to be underlined, but the field, whether it's empty or full of text.

An example is seen in this example of Google Material Design:

enter image description here

So of course I could just stick in a UIImage that shows a solid color and fit it to that space, but that doesn't seem quite elegant, is there a better way that's more "correct" and future-proof if I'm worrying about how my code will work several generations of iOS down the line and on who knows what devices?

p.s. would rather do this from scratch using Obj-C than find a library.

2

There are 2 answers

5
DBoyer On BEST ANSWER

I actually just did this yesterday... Subclass UITextField and this will work.

Note: It would be cleaner though to use textFieldDidBeginEditing: and textFieldDidEndEditing: to do the changing of the line height and color, either through NSNotificationCenter or delegate methods.

- (void)setup 
{
    self.hairlineLayer = [CALayer layer];
    self.hairlineLayer.backgroundColor = [UIColor materialTextDarkDividerColor].CGColor;
    [self.layer addSublayer:self.hairlineLayer];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat hairlineHeight = 0;
    if (self.isFirstResponder) {
        self.hairlineLayer.backgroundColor = [UIColor redColor].CGColor;
        hairlineHeight = 1.4;
    } else {
        self.hairlineLayer.backgroundColor = [UIColor grayColor].CGColor;
        hairlineHeight = 1/[UIScreen mainScreen].scale;
    }

    self.hairlineLayer.frame = CGRectMake(0, CGRectGetHeight(self.bounds) - hairlineHeight, CGRectGetWidth(self.bounds), hairlineHeight);
}
0
Premkumar On

Create a new GlobalClass

Declare a Method in GlobalClass.h

+(void)UnderLineStyleTextField:(UITextField *)textField;

Define a Method in GlobalClass.m

+(void)UnderLineStyleTextField:(UITextField *)textField
{
CALayer *textFieldbottomBorder = [CALayer layer];
textFieldbottomBorder.frame = CGRectMake(0.0f, textField.frame.size.height - 1, textField.frame.size.width, 1.0f);
textFieldbottomBorder.backgroundColor = [UIColor blackColor].CGColor;
[textField.layer addSublayer:textFieldbottomBorder];
}

Import GlobalClass in ViewController

Call GlobalClass Method From ViewDidLoad

[GlobalClass UnderLineStyleTextField:txtForgotPasswods];