Xcode 8 - Autolayouts Issue

2019-09-11 12:48发布

问题:

I am setting up basic UIView subclass with the new Xcode and came across weird behaviour. The subclassed view appears to load normally at the first glance:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
        if (self) {
            [self baseInit];
}
    return self;
}
- (void)awakeFromNib
{
    [super awakeFromNib];
    [self baseInit];
}

I started to build another container view in storyboards set to size of iPhone 6 as I own one. I had a bit complicated layout with quite few objects and even if I am good at setting constrains, it came out shifted.

So I started to experiment with simple view, to see where the problem is after the Xcode upgrade.

Simple exercise with 2 UIViews.

The preference setting was set to 1000 to each constrain and device was set to iPhone 6s.

But the result on iPhone 6/s or my device iPhone 6 is shifted:

So when I started to fiddle around, I have discovered that if set the storyboard device to iPhone SE, it will show the content correctly on both, iPhone 6 simulator and iPhone 6 device:

Wrong setting and now it's aligned. Have I missed something in the new Xcode version and how to work with autolayouts and constrains?

Thank you A.

回答1:

If baseInit is doing anything with UIViews and frame sizes you should call it inside viewDidLayoutSubviews. This is called after the view has been laid-out according to the view's constraints.

static dispatch_once_t oncePerLoadToken;

- (void)viewDidLoad {
    [super viewDidLoad];
    oncePerLoadToken = 0;
}

- (void)viewDidLayoutSubviews {
    dispatch_once(&oncePerLoadToken, ^{
        [self baseInit];
    });
}