Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 469
shubham mishra Avatar asked Jun 22 '16 13:06

shubham mishra


2 Answers

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];
like image 116
Ronak Chaniyara Avatar answered Sep 28 '22 14:09

Ronak Chaniyara


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)
like image 32
marosoaie Avatar answered Sep 28 '22 14:09

marosoaie