Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField Only Top And Bottom Border

I currently have a regular border. I would like to only have a top and bottom border.

How do I accomplish this?

Using the UITextField's layer property, I have the following code:

    self.layer.borderColor = [[UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f] CGColor];
    self.layer.borderWidth = 4.0f;

I have kind of got it to work by making my UITextField extra long, so that the user does not see the left and right borders, but I was just wondering if there was a better, less hackish way of doing this?

I have checked the docs, and changing a UITextField's borderStyle does not have this option.

From,

An iOS First Timer

like image 681
GangstaGraham Avatar asked Mar 22 '13 03:03

GangstaGraham


2 Answers

One approach I have found works good is using layers. Here's a snippet:

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

Hope this helps someone.

like image 155
user3075378 Avatar answered Nov 06 '22 17:11

user3075378


@user3075378's great & simple example in Swift

var bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0.0, textField.frame.size.height - 1, textField.frame.size.width, 1.0);
bottomBorder.backgroundColor = UIColor.blackColor().CGColor
textField.layer.addSublayer(bottomBorder)
like image 42
Sebyddd Avatar answered Nov 06 '22 16:11

Sebyddd