比如一个UIViewController中。今天看到PureLayout中看到是这样组织的:
- 在loadView 中初始化UIView并添加,最后调用setNeedsUpdateConstraints
- 在updateViewConstraints中设置NSLayoutConstraints,并在最后调用[super updateViewConstraints],另外,为了不重复调用,用到了BOOL didSetupConstraints。
- (void)loadView
{
self.view = [UIView new];
[self.view addSubview:self.blueView];
[self.view addSubview:self.redView];
[self.view addSubview:self.yellowView];
[self.view addSubview:self.greenView];
[self.view setNeedsUpdateConstraints]; // bootstrap Auto Layout
}
- (void)updateViewConstraints
{
if (!self.didSetupConstraints) {
// Apply a fixed height of 50 pt to two views at once, and a fixed height of 70 pt to another two views
[@[self.redView, self.yellowView] autoSetViewsDimension:ALDimensionHeight toSize:50.0];
[@[self.blueView, self.greenView] autoSetViewsDimension:ALDimensionHeight toSize:70.0];
self.didSetupConstraints = YES;
}
[super updateViewConstraints];
}
问题来了:
1. 如果我在loadView中添加Constraints,这样肯定是添加一次的,也省得用didSetupConstraints了,不是更好吗?这样会有什么问题吗?
2. [super updateViewConstraints];为什么放到了updateViewConstraints的最后面,放在最前面会有什么问题呢?
PS: 在PureLayout的 Tips-and-Tricks中提到了上面的做法,很可惜并没有说明原因,所以询问一下大家的看法。