The correct way to implement updateConstraints

What part of my restrictions should I update in the updateConstraints method? Should I update all restrictions associated with my subclass? In my UIView subclass, I usually add an array of constraints that apply only to the subviews 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 will be no clashes between my constraints, superclass constraints or subclass constraints.

Question: should I update all self.subclassConstraints? Or should I only update restrictions that may be incorrect after some actions?

If there is some kind of property, and someone can reset them or assign nil, I think that all related restrictions will be wrong, so I have to update the restrictions of this view in each - (void)updateConstraints .

fe

 @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 restrictions in the updateConstraints method? Or I need to update only some of them (like imageViewConstraints, for example)

+7
ios objective-c nslayoutconstraint uiview
source share
1 answer

Ultimately, this will depend on how your views are positioned using autostart and what restrictions will cause a conflict / s when your view is changed. This will vary from case to case.

Always consider how your layout is affected as a whole for each edge case, and not just for one resized view. Sometimes only subview changes need to be changed, as in your example. However, there are also times when restrictions on the entire layout also need to be updated.

If possible, it is always more efficient to change only those constraints that are necessary to make your layout valid, because you are reusing existing constraints instead of creating new ones. And, by changing, I do not necessarily mean simply breaking down and re-creating restrictions. If you can, just change the constant value of the constraints that you need to make your layout valid.

+2
source share

All Articles