我使用PureLayout
在UIView中实现子视图的自动布局。但是我不知道组织代码的最佳实践。
我应该把自动布局相关的代码在init的UIView,或覆盖的方法,如updateConstraints
和layoutSubviews
?
例如,我想创建一个名为PHView的UIView子类,对于任何PHView,都有一个名为centerView的子视图,它总是在PHView的中心,宽度/高度是0.3* PHView的宽度/高度。https://www.dropbox.com/s/jaljggnymxliu1e/IMG_3178.jpg
#import "PHView.h"
#import "Masonry.h"
@interface PHView()
@property (nonatomic, assign) BOOL didUpdateConstraints;
@property (nonatomic, strong) UIView *centerView;
@end
@implementation PHView
- (instancetype)init {
self = [super init];
if (self) {
self.backgroundColor = [UIColor redColor];
self.translatesAutoresizingMaskIntoConstraints = NO;
}
return self;
}
- (UIView *)centerView {
if (!_centerView) {
_centerView = [UIView new];
_centerView.backgroundColor = [UIColor yellowColor];
[self addSubview:_centerView];
}
return _centerView;
}
-(void)updateConstraints {
if (!_didUpdateConstraints) {
_didUpdateConstraints = YES;
[self.centerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.mas_centerX);
make.centerY.equalTo(self.mas_centerY);
make.width.equalTo(self.mas_width).multipliedBy(0.3);
make.height.equalTo(self.mas_height).multipliedBy(0.3);
}];
}
[super updateConstraints];
}
@end
'didUpdateConstraints'旨在表明您已经添加了约束,所以您将只添加约束一次。
在UIViewController中:make phview top bottom left right 20 to margin.
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
PHView *myView = [PHView new];
[self.view addSubview:myView];
[myView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(20, 20, 20, 20));
}];
}
当您确定view
已经添加到它的superview
中时,您应该添加constraints
。基本上,您应该在调用addSubview:
之后的任何点在superview
的类中执行此操作。
回答你的问题:
1-在init
方法中,你能确定view
已经作为subview
添加到superview
了吗?这样假设是不安全的。也许你可以在superview
的init
方法中添加constraints
2- layoutSubviews
在autolayout
代码实际工作的地方。layoutSubviews
中不能添加constraints
。已经使用autolayout
constraints
并不便宜,因此你应该尽可能少地添加/删除它们,在多次调用的方法中这样做(即layoutSubviews
)不是最佳实践。
autolayout
的机制是从外部view
到内部view
,因此subviews
实际上并不关心constraints
。superview
的责任
希望这能帮助你理解控制器的视图层次结构视图控制器如何参与视图布局过程
- 视图控制器的视图被调整为新的大小。
- 如果未使用自动布局,则视图根据其自动调整大小的蒙版调整大小。
- 视图控制器的viewWillLayoutSubviews方法被调用。
-
视图的layoutSubviews方法被调用。如果使用autolayout来配置视图层次结构,它会通过执行以下步骤来更新布局约束:
。视图控制器的updateViewConstraints方法被调用。
b。UIViewController类的updateViewConstraints方法的实现调用了视图的updateConstraints方法。
c。更新布局约束后,计算新的布局并重新定位视图。
-
视图控制器的viewDidLayoutSubviews方法被调用。
详情请参考