How to create underlined UITextField

@Ashish Kakkad has posted the right code but the reason it might not be working for @user1406716 is because when there is no text in the textfield, the height and width of the frame are 0 so maybe you can try the following :

Obj-C :

CALayer *bottomLine = [CALayer layer];
bottomLine.frame = CGRectMake(0.0f, 75 - 1, 300, 1.0f);
bottomLine.backgroundColor = [UIColor whiteColor].CGColor;
[myTextField setBorderStyle:UITextBorderStyleNone];
[myTextField.layer addSublayer:bottomLine];

Swift :

var bottomLine = CALayer()
bottomLine.frame = CGRectMake(0.0, 75 - 1, 300, 1.0)
bottomLine.backgroundColor = UIColor.whiteColor().CGColor
myTextField.borderStyle = UITextBorderStyle.None
myTextField.layer.addSublayer(bottomLine)

This will ensure that the line is visible even when there is no text in the textfield.


Try this code :

Obj-C

CALayer *bottomLine = [CALayer layer];
bottomLine.frame = CGRectMake(0.0f, self.frame.size.height - 1, self.frame.size.width, 1.0f);
bottomLine.backgroundColor = [UIColor whiteColor].CGColor;
[myTextField setBorderStyle:UITextBorderStyleNone];
[myTextField.layer addSublayer:bottomLine];

Swift

var bottomLine = CALayer()
bottomLine.frame = CGRectMake(0.0, view.frame.height - 1, view.frame.width, 1.0)
bottomLine.backgroundColor = UIColor.whiteColor().CGColor
myTextField.borderStyle = UITextBorderStyle.None
myTextField.layer.addSublayer(bottomLine)

Hope it helps

If you are using the auto-layout then try to do this code inside the viewDidLayoutSubviews method.