bradford gray bradford gray - 10 months ago 68
iOS Question

Show bottom border of UITextField in Swift not working with Constraints.

My code to show the bottom border only works if I don't use any constraints. As soon as I do so, the bottom line disappears. Any reasons, or solution do this problem? Here is my current code. I've seen quite a few answers to solution, but none are working when I add constraints.

func useUnderline() {

var bottomLine = CALayer()

bottomLine.frame = CGRect(x: 0.0, y: self.frame.height - 1, width: self.frame.width, height: 1)
bottomLine.backgroundColor = UIColor.white.cgColor
self.borderStyle = UITextBorderStyle.none


Answer Source

Any reasons

Certainly there's a reason. The constraints resize your view (self). But they do not resize or reposition the layer. So the bottom border is now in the wrong place, possibly outside the view. Your code depends upon self.frame, but constraints change self.frame.

none are working when I add constraints

Well, it's pretty simple. You need to implement layoutSublayersOfLayer in your view, and lay out the border layer there so that it stays where you want it.