How to force layoutSubviews of UIView? How to force layoutSubviews of UIView? ios ios

How to force layoutSubviews of UIView?


Had a similar problem today. I solved it by first calling

  • -setNeedsLayout: Set the flag that the view needs layout, and afterwards calling
  • -layoutIfNeeded: Check the flag immediately and - as it was set manually before - as result layoutSubviews is called.

Don't know if this is the best way, but it works ;)


I would suggest setting the initial frame in viewDidLoad then changing the view frame for orientation changes in

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

You don't need any explicit animations in layoutSubviews (not sure if you had any, but it sounded like it) as any frame changes will be synced to the rotation animation.

When off screen the orientation should still be rotated, so your views should be positioned correctly when transitioned back on screen again.

I also recommend watching WWDC 2010 Session 123 "Building Animation Driven UI" which covers this stuff in much more detail.


At swift 3 @iOS 10.1

override func viewWillAppear(animated: Bool){    super.viewWillAppear(animated)    view.setNeedsLayout()}

runs perfect