3

I am changing some constraints and hiding some elements on a certain VC depending on what device the user is using.

Like this:

   override func viewDidLayoutSubviews() {
        if Iphone6 == true {
            self.view.layoutIfNeeded()
            self.someConst.constant = 70
            self.anotherConst.constant = 67
            self.someButton.hidden = true
            self.someView.hidden = true
            self.view.layoutIfNeeded()
        }   
   }

Now I wonder if I need to call layoutIfNeeded() twice in viewDidLayoutSubviews ?

I do know that you have to call layoutIfNeeded() twice if you are using animateWithDuration when changing constraints but this it also apply to viewDidLayoutSubviews?

Thanks,

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
user2636197
  • 3,982
  • 9
  • 48
  • 69

1 Answers1

4

The purpose of layoutIfNeeded() is to force a synchronous (essentially "immediate") redraw of a view and its subviews. When dealing with animations, Apple considers it best practice to call layoutIfNeeded() prior to the animation block to ensure pending layout operations have fully completed. This prepares the views for the operations to determine and set their new layouts. layoutIfNeeded() is then called a second time within the animation block to ensure the animated changes to the layout are also completed.

Apple's documentation for viewDidLayoutSubviews() expresses that this method being called does not indicate that the individual layouts of the view'€™s subviews have been adjusted. So when you start to check the device being used and adjust the layout accordingly, there's no guarantee all prior layout operations have completed successfully. For that reason, it's a good idea for you to continue to call layoutIfNeeded() twice. Once to make sure any previous layout operations are wrapped up and once again to enact the layout changes you've made based on the device type.

Sources:

How do I animate constraint changes?

setNeedsLayout vs layoutIfNeeded Explained

viewDidLayoutSubviews Reference

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Ian Rahman
  • 315
  • 3
  • 7