如何以编程方式从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.

希望这会有所帮助:)