Search code examples
swiftautolayout

Swift text field border isn't the right width


I have a bottom border that I generated after following the answer here.

This works absolutely great except the border isn't the right width. It's set with constraints to match the width of the button below it but as you can see is coming up short.

What am I missing?

Code :

extension UITextField
{
    func setBottomBorder(withColor color: UIColor)
    {
        self.borderStyle = UITextBorderStyle.none
        self.backgroundColor = UIColor.clear
        let width: CGFloat = 3.0

        let borderLine = UIView(frame: CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width))
        borderLine.backgroundColor = color
        self.addSubview(borderLine)
    }
}

then in the VC :

override func viewDidLoad() {

        authorNameOutlet.setBottomBorder(withColor: UIColor.lightGray)
    }

Then Xcode shows...

enter image description here

but the simulator shows...

enter image description here

I've tried this both setting the width of the text field to be 0.7 x the superview width (same as the button below it) and also setting the width of the text field to be equal width of the button but neither works.


Solution

  • This is because of AutoLayout.

    You can add autoresizingMask to your line.

    borderLine.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]