我应该把自动布局代码放在哪里



我使用PureLayout在UIView中实现子视图的自动布局。但是我不知道组织代码的最佳实践。

我应该把自动布局相关的代码在init的UIView,或覆盖的方法,如updateConstraintslayoutSubviews ?

例如,我想创建一个名为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了吗?这样假设是不安全的。也许你可以在superviewinit方法中添加constraints

2- layoutSubviewsautolayout代码实际工作的地方。layoutSubviews中不能添加constraints。已经使用autolayout constraints并不便宜,因此你应该尽可能少地添加/删除它们,在多次调用的方法中这样做(即layoutSubviews)不是最佳实践。

autolayout的机制是从外部view到内部view,因此subviews实际上并不关心constraintssuperview的责任

希望这能帮助你理解控制器的视图层次结构视图控制器如何参与视图布局过程

  1. 视图控制器的视图被调整为新的大小。
  2. 如果未使用自动布局,则视图根据其自动调整大小的蒙版调整大小。
  3. 视图控制器的viewWillLayoutSubviews方法被调用。
  4. 视图的layoutSubviews方法被调用。如果使用autolayout来配置视图层次结构,它会通过执行以下步骤来更新布局约束:

    。视图控制器的updateViewConstraints方法被调用。

    b。UIViewController类的updateViewConstraints方法的实现调用了视图的updateConstraints方法。

    c。更新布局约束后,计算新的布局并重新定位视图。

  5. 视图控制器的viewDidLayoutSubviews方法被调用。

详情请参考

相关内容

最新更新