3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
nc14
  • 539
  • 1
  • 8
  • 26

2 Answers2

3

This is because of AutoLayout.

You can add autoresizingMask to your line.

borderLine.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
Kirow
  • 1,077
  • 12
  • 25
2

You are working with with a static frame for the border line view. After viewDidLoad your view controller's view gets resized.

Option 1: (Fast and dirty)

Move your code from viewDidLoad() to viewWillAppear(_ animated: Bool). viewWillAppear gets called after the first layout of your view controller's view

Option 2:

Add constraint for your border line view. So that your border line view will resize automatically.

Importent hint:

Do not forget super calls in overrides or you will get strange bugs!

E.g:

override func viewDidLoad() {
    super.viewDidLoad()
    // your code
}
Johannes
  • 564
  • 2
  • 7