我想从 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
最佳答案
您可以在 NSArray
中获取约束,例如,
NSArray *constraintArr = self.backButton.constraints;
NSLog(@"cons : %@",constraintArr);
你可以像这样设置实例变量,
NSLayoutConstraint *titleLabelBottom;
然后使用,
titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];
[self addConstraints:@[titleLabelBottom]];
因此,您可以在类里面的任何地方使用 titleLabelBottom
。
希望这会有所帮助:)
关于ios - 如何以编程方式从 UIView 获取约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641487/