【发布时间】:2016-08-07 02:13:12
【问题描述】:
我想从 UIView 获得 UILabel 约束,但我无法获得任何约束。 我在 CustomView.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
}
在 ViewController.m 中
CustomView *view = [CustomView alloc] initWithFrame:viewFrame];
NSLog(@"%@",view.titleLabel.constraints); // nil
【问题讨论】:
-
layoutSubviews:被多次调用,你总是创建一个新的约束。将约束创建移动到您的初始化程序
标签: ios objective-c uiview autolayout nslayoutconstraint