Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift make input transparent with only border-bottom

Tags:

ios

swift

How can I create a textField with transparent background and only border bottom?

I have tried this code:

textField.backgroundColor = .clear
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGrayColor().CGColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)
border.borderWidth = width
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true

But it isn't working.

like image 850
user7444742 Avatar asked Dec 06 '25 06:12

user7444742


2 Answers

Here's an alternative implementation using a UIView rather than a CALayer.

let line = UIView()
line.frame.size = CGSize(width: textField.frame.size.width, height: 1)
line.frame.origin = CGPoint(x: 0, y: textField.frame.maxY - line.frame.height)
line.backgroundColor = UIColor.darkGray
line.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
textField.addSubview(line)
like image 191
Mobile Dan Avatar answered Dec 07 '25 20:12

Mobile Dan


Your code is correct. Problem is only with your border height which is now "textField.frame.size.height" change it to 1.0.(Change your border frame code).

like image 29
Tejas Shelke Avatar answered Dec 07 '25 21:12

Tejas Shelke