Search code examples
iosswiftnslayoutconstraintnslayoutanchor

Is using NSLayoutAnchor bad?


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:

let myView = UIView(frame: CGRect(x: 0, y: 20, width: view.frame.bounds.width, height: 100))

Instead of:

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

Solution

  • First of all, I want to confirm that using frame is much faster than auto layout (~10 times as I know). That's why another one told you to use frame instead of auto layout. While @RakeshaShastri had a good answer to explain why we should use auto layout, my answer will talk about when you should use frame instead of auto layout.


    • When displaying normal view such as UIView, UIButton, UILabel... on view controller, you can use auto layout. The difference between using frame and auto layout is trivial.
    • With UICollectionViewCell and UITableViewCell, you should use frame. There is a big difference about performance between frame and auto layout in this case.

    Let's take a look at below benchmark to compare them.

    The picture is taken from LayoutFrameworkBenchmark. It shows performance when layouting 100 UICollectionView cells

    enter image description here

    As you can see, auto layout takes much more time than Manual Layout and Not Auto Layout (~15 times). The difference will affect how smooth your collection view is when it's scrolled.

    Specially when your cell has heavy view hierarchy, auto layout will take a lot of time to calculate positions of cell's subview base on constraints with superfluous calculations. It can make collection view or table view lagging while scrolling. Using frame here is a away to reduce superfluous calculations as much as possible and help us save times for another tasks.


    Conclusions:

    • Be careful when using auto layout on UICollectionViewCell, UITableViewCell. If your collection view or table view isn't smooth while scrolling, auto layout maybe a big reason.

    • Use frame only when you have trouble with auto layout. Performance gained from using frame in normal case is trivial.