0

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?

mrgs
  • 3
  • 2
  • We generally fall back to `viewDidLayoutSubviews` for those things that cannot easily be changed with constraints. E.g., for those manual adjustments that are necessary as a result of changing view size, such as updating corner radii, updating bezier paths, etc. But for those items that can be accomplished with constraints, constraints are generally preferable to manual adjustments in `viewDidLayoutSubviews` (or `UIView` method `layoutSubviews`). – Rob Sep 13 '22 at 22:04

1 Answers1

0

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.

Vikram Parimi
  • 777
  • 6
  • 29