Question

Which part of my constraints I should update in updateConstraints method? Should I update all constraints related to my subclass? In my UIView subclass I usual add array of constraints related only on subviews that defined in this subclass.

@property(nonatomic, strong) NSArray *subclassConstraints;

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

So, there won't be any collisions between my constraints, super class constraints or subclass constraints.

The question is: Should I update all self.subclassConstraints ? Or I should update only constraints that could be incorrect after some actions?

If there is some view property, and some one can reset them or assign nil, I think that all related constraints will be incorrect, so I should update constraints of that view in every - (void)updateConstraints call.

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];
}

So should I update all my constraints in updateConstraints method? Or should I update only some of them (f.e. like imageViewConstraints)

Was it helpful?

Solution

Ultimately, it's going to depend on how your views are positioned using autolayout and which constraints will cause conflict/s when your subview is modified. It's going to vary on a case per case basis.

Always take note of how your layout is affected as a whole for every edge case and not just for the single view that changed. Sometimes only the subview's constraints need to change like in your example. However, there are also times when constraints for the whole layout also need to be updated.

If you can, it's always more efficient to change only the constraints that you need to make your layout valid because you're reusing existing constraints instead of creating new ones. And by change, I don't necessarily mean just destroying and recreating constraints. If you can, just change the constant value of the constraints that you need to make your layout valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top