我想从UIView获取UILabel约束,但我无法获得任何约束。 我设置的约束在CustomView.m这样的:如何以编程方式从UIView获取约束
在ViewController.m- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_titleLabel = [UILabel new];
[self addSubview:_titleLabel];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];
[self addConstraints:@[titleLabelBottom]];
...more code
}
CustomView *view = [CustomView alloc] initWithFrame:viewFrame];
NSLog(@"%@",view.titleLabel.constraints); // nil
'layoutSubviews:'被调用很多次,并且您总是创建一个新的约束。将约束创建移动到您的初始化程序 – tgyhlsb