The difference between viewDidLayoutSubviews and NSLayoutConstraint

32 Views Asked by At

Please explain the difference. I watch the lesson on YouTube (LINK)

The guy uses viewDidLayoutSubviews when he could have used NSLayoutConstraint.

 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    firstNameField.frame = CGRect(x: 30,
                                  y: imageView.bottom+10,
                                  width: scrollView.width-60,
                                  height: 52)
}

example NSLayoutConstraint.activate

 NSLayoutConstraint.activate([
        firstNameField.heightAnchor.constraint(equalToConstant: 52),
        firstNameField.bottomAnchor.constraint(equalTo: imageView.bottomAnchor, constant: -10),
        and e.t.c
        
    ])

I haven't used viewDidLayoutSubviews before, which is the right approach?

1

There are 1 best solutions below

0
Vikram Parimi On

The constraint approach/Autolayout is preferred over setting a frame manually with the values. Following a constraint approach offers you flexibility in terms of managing your layout dynamically based on the nearby views, size classes and also multiplier based constraints can be used to adjust the view based on the screen size or view sizes relatively.

Constraint Approach advantages:

  • Dynamic layout
  • Size classes/Traits
  • Relative layout
  • Priorities
  • Intrinsic sizing
  • When you are supporting multiple form factors it comes easy whereas the frame based approach might need re-work

The method viewDidLayoutSubviews is a callback function that is notified once the view adjusts the position of all it's views.

Apple Documentation

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout. Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing.

To answer your question - it depends on what you want to achieve by knowing the subviews are adjusted after notified via viewDidLayoutSubviews

Even inside the method viewDidLayoutSubviews you can use constraints over frames.