如何以编程方式从UIView获取约束 [英] How to get constraints from UIView Programmatically
本文介绍了如何以编程方式从UIView获取约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从UIView获取UILabel约束,但是我无法获得任何约束. 我像这样在CustomView.m中设置约束:
I want get UILabel constraints from UIView but I can't get any constraints. I set the constraints in CustomView.m like this:
- (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
in ViewController.m
CustomView *view = [CustomView alloc] initWithFrame:viewFrame];
NSLog(@"%@",view.titleLabel.constraints); // nil
推荐答案
您可以在NSArray
之类的条件中获得约束,
you can get constraints in NSArray
like,
NSArray *constraintArr = self.backButton.constraints;
NSLog(@"cons : %@",constraintArr);
您可以将实例变量设置为
And you can set instance variable like,
NSLayoutConstraint *titleLabelBottom;
然后使用
titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];
[self addConstraints:@[titleLabelBottom]];
因此,您可以在课堂上的任何地方使用titleLabelBottom
.
so, you can use titleLabelBottom
anywhere in class.
希望这会有所帮助:)
这篇关于如何以编程方式从UIView获取约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文