0

I am using storyboard for UI builder, and I added this in viewDidLoad. But the bottom border doesn't go all the way the "EnteredEmail.frame.width" equals the size of the textfield in the storyboard which is iPhone SE

    override func viewDidLoad() {
        super.viewDidLoad()
        let EmailBottomLine = CALayer()
        EmailBottomLine.frame = CGRect(x: 0.0, y: EnteredEmail.frame.height-5, width: EnteredEmail.frame.width, height: 5)
        EmailBottomLine.backgroundColor = UIColor.black.cgColor
        EnteredEmail.layer.addSublayer(EmailBottomLine)
    }

enter image description here

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
TomatoRage
  • 23
  • 3
  • When viewDidLoad is called the views aren't laid out so the frames are in accurate. Try moving your code to viewDidAppear or viewWillLayoutSubviews. – Rob C Aug 30 '20 at 04:55
  • I don't know about how you implemented ```EnteredEmail```. But from my opinion. Your viewController should have no knowledge about how ```EnteredEmail``` drawing. If you really want the so-called bottom border. Do this layer configuration in the ```EnteredEmail``` view itself. It does have some lifecycle function like ```layoutSublayers(of:)``` which I think it's better place to do this sort of things like adjusting sublayer's ```frame```, etc. – zhoujialei Aug 30 '20 at 08:55

1 Answers1

-2

Simply you need to move your code to viewDidAppear() instead of viewWilllayoutSubviews().

viewDidAppear(_ animated: Bool) This is called when the screen is shown to the user. This is a good place to put code where you might need to get the position of elements on the screen and run animations.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let EmailBottomLine = CALayer()
    EmailBottomLine.frame = CGRect(x: 0.0, y: EnteredEmail.frame.height-5, width: EnteredEmail.frame.width, height: 5)
    EmailBottomLine.backgroundColor = UIColor.black.cgColor
    EnteredEmail.layer.addSublayer(EmailBottomLine)
}
Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
  • `viewWilllayoutSubviews` was literally made to "When a view's bounds change, the view adjusts the position of its subviews. Your view controller can override this method to make changes before the view lays out its subviews". check apple documentation – Mohmmad S Aug 30 '20 at 07:57
  • why would you use a lifecycle function for this ? – Mohmmad S Aug 30 '20 at 07:58
  • The viewDidAppear event fires after the view is presented on the screen. Which makes it a good place to get data from a backend service or database. Called when the view has been fully transitioned onto the screen. Default does nothing. To know more you can see this: https://stackoverflow.com/questions/5562938/looking-to-understand-the-ios-uiviewcontroller-lifecycle @MohmmadS – Faysal Ahmed Aug 30 '20 at 11:50