Is using NSLayoutAnchor bad?

ssmeter

New Member
#1
I usually use NSLayoutAnchor but many times I have been advised to not use it. Is there any problem with it such as performance drop besides more complex/longer code?
I've been told to use:
Mã:
let myView = UIView(frame: CGRect(x: 0, y: 20, width: view.frame.bounds.width, height: 100))
Instead of:
Mã:
let myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
myView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
myView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
myView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
 

Admin

Administrator
Thành viên BQT
#2
The drawback of using frames is that once you lay them out, you need to manually change them whenever you need it to change relative to something. eg: Orientation change, animation, etc. But if you use autolayout, you would be defining the position of the view relatively which means, even in the case of orientation changes or animations, your view will resize itself according to the constraints you set.

Regarding the performance drop, autolayout takes more time (not that much) to calculate the frame of a view, but this would be negligible and the convenience way overshadows the performance impact.

In the end, the use case for frames would be very very small considering the fact that most of the views would need some kind of dynamic positioning based on screen size, orientation change, etc. And mixing frames and autolayout is never a good idea.

Tl;dr - Autolayout > frames.
 
Top