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 ?
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];
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With