shubham mishra
shubham mishra

Reputation: 991

UITextField having bottom border only in Objective-C

I am creating UITextField programatically and i am trying to create a textField that has only bottom border as given in the figure. Please help this problem in objective-c programatically ?

enter image description here

Upvotes: 6

Views: 5220

Answers (2)

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5435

First:

Add and import QuartzCore framework.

#import <QuartzCore/QuartzCore.h>

Second:

CALayer *border = [CALayer layer];
CGFloat borderWidth = 2;
border.borderColor = [UIColor grayColor].CGColor;
border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
border.borderWidth = borderWidth;
[textField.layer addSublayer:border];
textField.layer.masksToBounds = YES;

EDIT:

If you have more TextFields, make one common method which takes UITextField and applies border to it like below:

-(void)SetTextFieldBorder :(UITextField *)textField{

    CALayer *border = [CALayer layer];
    CGFloat borderWidth = 2;
    border.borderColor = [UIColor grayColor].CGColor;
    border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
    border.borderWidth = borderWidth;
    [textField.layer addSublayer:border];
    textField.layer.masksToBounds = YES;

}

Pass your TextField as follows to set Bottom Border:

[self SetTextFieldBorder:YourTextField];

Upvotes: 10

marosoaie
marosoaie

Reputation: 2371

Or you can add a thin line subview to the textfield that will mimic the border:

UIView *lineView = [[UIView alloc] init];
lineView.translatesAutoresizingMaskIntoConstraints = false;
lineView.backgroundColor = [UIColor grayColor];
[textField addSubview:lineView];

[lineView.heightAnchor constraintEqualToConstant:1];
[lineView.leftAnchor constraintEqualToAnchor:textField.leftAnchor constant:5.0];
[lineView.rightAnchor constraintEqualToAnchor:textField.rightAnchor constant:-5.0];
[lineView.bottomAnchor constraintEqualToAnchor:textField.bottomAnchor constant:0.0];

Swift version:

let lineView = UIView()
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.backgroundColor = UIColor.grayColor()
textField.addSubview(lineView)

lineView.heightAnchor.constraintEqualToConstant(1)
lineView.leftAnchor.constraintEqualToAnchor(textField.leftAnchor)
lineView.rightAnchor.constraintEqualToAnchor(textField.rightAnchor)
lineView.bottomAnchor.constraintEqualToAnchor(textField.bottomAnchor)

Upvotes: 1

Related Questions