UITextField Only Top And Bottom Border
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.
@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().CGColortextField.layer.addSublayer(bottomBorder)
@Sebyddd why stop there? (;
EDIT: There is an issue with lines being drawn before auto layout sets the right frame for the view, I edited my answer with a fix: it basically involves calling drawLines()
in layoutSubviews()
:
class FramedTextField: UITextField { @IBInspectable var linesWidth: CGFloat = 1.0 { didSet{ drawLines() } } @IBInspectable var linesColor: UIColor = UIColor.blackColor() { didSet{ drawLines() } } @IBInspectable var leftLine: Bool = false { didSet{ drawLines() } } @IBInspectable var rightLine: Bool = false { didSet{ drawLines() } } @IBInspectable var bottomLine: Bool = false { didSet{ drawLines() } } @IBInspectable var topLine: Bool = false { didSet{ drawLines() } } func drawLines() { if bottomLine { add(CGRectMake(0.0, frame.size.height - linesWidth, frame.size.width, linesWidth)) } if topLine { add(CGRectMake(0.0, 0.0, frame.size.width, linesWidth)) } if rightLine { add(CGRectMake(frame.size.width - linesWidth, 0.0, linesWidth, frame.size.height)) } if leftLine { add(CGRectMake(0.0, 0.0, linesWidth, frame.size.height)) } } typealias Line = CGRect private func add(line: Line) { let border = CALayer() border.frame = line border.backgroundColor = linesColor.CGColor layer.addSublayer(border) } override func layoutSubviews() { super.layoutSubviews() drawLines() }}