Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force layoutSubviews of UIView?

People also ask

How do I force layoutSubviews?

If you want to force a layout update, call the setNeedsLayout() method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded() method.

When should I call layoutSubviews?

If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes. Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview .

How many times viewDidLayoutSubviews called?

Ans : ViewDidLoad called once only when all views are loaded. viewDidLayoutSubviews : Apple gave a very good explanation on this by saying that it is called to notify the view controller that its view has just laid out its subviews.

What is layoutIfNeeded in Swift?

layoutIfNeeded()Lays out the subviews immediately, if layout updates are pending.


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