I wrote codes like these that works well
@interface SubView()
@property(nonatomic,strong) UIButton* btn;
@end
@implementation SubView
- (void)layoutSubviews
{
[super layoutSubviews];
[self.btn removeFromSuperview];
self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
self.btn.backgroundColor = [UIColor greenColor];
[self.btn setTitle:@"btn" forState:UIControlStateNormal];
self.btn.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:self.btn];
NSLayoutConstraint* centerXConstraint = [self.btn.centerXAnchor constraintEqualToAnchor:self.centerXAnchor];
NSLayoutConstraint* centerYConstraint = [self.btn.centerYAnchor constraintEqualToAnchor:self.centerYAnchor];
[self addConstraint:centerXConstraint];
[self addConstraint:centerYConstraint];
}
@end
But in my opinion,When using Autolayout, the system will do the layout in two steps 1 Update Pass 2 Layout Pass , and the layoutSubviews is in the step 2(Layout Pass)
so if we add subview in layoutSubviews ,it seems like it will change the view's constraints , so we need do the update pass and layout pass again , so it will generate a infinite loop ..
but in fact , this code works well , so where am i wrong?
Keep in mind that layoutSubviews will be called many times. What sense does it make to remove the button and add it again every single time?
Also, layoutSubviews is where the autolayout system obeys constraints. So what sense does it make to set the button's constraints in layoutSubviews?
Even if it seems to be working, none of what you are doing makes any sense in layoutSubviews. Do this task once and do it elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With