实现updateConstraints的正确方法

时间:2014-04-23 09:21:04

标签: ios objective-c uiview nslayoutconstraint

我应该在updateConstraints方法中更新哪些部分约束? 我应该更新与我的子类相关的所有约束吗? 在我的UIView子类中,我通常会添加仅与此子类中定义的子视图相关的约束数组。

@property(nonatomic, strong) NSArray *subclassConstraints;

- (void)updateConstraints {
 [self removeConstraints:self.subclassConstraints];
 self.subclassConstraints = [self createConstraints];
 [self addConstraints:self.subclassConstraints];
 [super updateConstraints];
}

因此,我的约束,超类约束或子类约束之间不会发生任何冲突。

问题是:我应该更新所有self.subclassConstraints吗? 或者我应该只更新一些操作后可能不正确的约束?

如果有一些视图属性,有些可以重置它们或指定nil,我认为所有相关的约束都是不正确的,所以我应该更新每个视图的约束 - (void)updateConstraints致电。

f.e。

@property (nonatomic, strong) UIImageView *imageSubview;


- (void)setImageSubview:(UIImageView *)imageView {
    if (![_imageView isEqual:imageView]) {
        _imageView = imageView;
        [self setNeedUpdateConstraints];
    }
}

- (void)updateConstraints {
    [self removeConstraints:self.imageViewConstraints];
    self.imageViewConstraints = [self createImageViewConstraints];
    [self addConstraints:self.imageViewConstraints];
    [super updateConstraints];
}

那么我应该更新updateConstraints方法中的所有约束吗? 或者我应该只更新其中一些(例如imageViewConstraints)

1 个答案:

答案 0 :(得分:2)

最终,它将取决于您使用自动布局定位视图的方式以及修改子视图时哪些约束会导致冲突。它会根据具体情况而有所不同。

始终注意每个边缘情况的布局如何受到影响,而不仅仅是针对单个视图的更改。有时只有子视图的约束需要像您的示例中那样进行更改。但是,有时候还需要更新整个布局的约束。

如果可以的话,只更改使布局有效所需的约束总是更有效率,因为您重复使用现有约束而不是创建新约束。通过改变,我不一定意味着只是破坏和重建约束。如果可以,只需更改使布局有效所需的约束的常量值。