Since Xcode 8 and iOS10, views are not sized properly on viewDidLayoutSubviews

Solution: Wrap everything inside viewDidLayoutSubviews in DispatchQueue.main.async.

// swift 3

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    DispatchQueue.main.async {
        // do stuff here
    }
}

Now, Interface Builder lets the user change dynamically the size of every view controllers in storyboard, to simulate the size of a certain device.

Before this functionality, the user should set manually each view controller size. So the view controller was saved with a certain size, which was used in initWithCoder to set the initial frame.

Now, it seems that initWithCoder do not use the size defined in storyboard, and define a 1000x1000 px size for the viewcontroller view & all its subviews.

This is not a problem, because views should always use either of these layout solutions:

  • autolayout, and all the constraints will layout correctly your views

  • autoresizingMask, which will layout each view which doesn't have any constraint attached to (note autolayout and margin constraints are now compatible in the same view \o/ !)

But this is a problem for all layout stuff related to the view layer, like cornerRadius, since neither autolayout nor autoresizing mask applies to layer properties.

To answer this problem, the common way is to use viewDidLayoutSubviews if you are in the controller, or layoutSubview if you are in a view. At this point (don't forget to call their super relative methods), you are pretty sure that all layout stuff has been done!

Pretty sure? Hum... not totally, I've remarked, and that's why I asked this question, in some cases the view still has its 1000x1000 size on this method. I think there is no answer to my own question. To give the maximum information about it:

1- it happends only when laying out cells! In UITableViewCell & UICollectionViewCell subclasses, layoutSubview won't be called after subviews would be correctly layed out.

2- As @EugenDimboiu remarked (please upvote his answer if useful for you), calling [myView layoutIfNeeded] on the not-layed out subview will layout it correctly just in time.

- (void)layoutSubviews {
    [super layoutSubviews];
    NSLog (self.myLabel); // 1000x1000 size 
    [self.myLabel layoutIfNeeded];
    NSLog (self.myLabel); // normal size
}

3- To my opinion, this is definitely a bug. I've submitted it to radar (id 28562874).

PS: I'm not english native, so feel free to edit my post if my grammar should be corrected ;)

PS2: If you have any better solution, feel free not write another answer. I'll move the accepted answer.


Are you using rounded corners for your button ? Try calling layoutIfNeeded() before.