shubham mishra shubham mishra - 2 months ago 20
Objective-C Question

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

Answer

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];
Comments