我想從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