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?
The constraint approach/
Autolayoutis 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:
The method
viewDidLayoutSubviewsis a callback function that is notified once the view adjusts the position of all it's views.Apple Documentation
To answer your question - it depends on what you want to achieve by knowing the subviews are adjusted after notified via
viewDidLayoutSubviewsEven inside the method
viewDidLayoutSubviewsyou can use constraints over frames.