How to get constraints from UIView Programmatically

时光毁灭记忆、已成空白 提交于 2019-12-08 19:21:03

问题


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

}

in ViewController.m

 CustomView *view = [CustomView alloc] initWithFrame:viewFrame];
 NSLog(@"%@",view.titleLabel.constraints); // nil

回答1:


you can get constraints in NSArray like,

NSArray *constraintArr = self.backButton.constraints;
NSLog(@"cons : %@",constraintArr);

And you can set instance variable like,

NSLayoutConstraint *titleLabelBottom;

and then use,

titleLabelBottom = [NSLayoutConstraint constraintWithItem:_titleLabel
                                          attribute:NSLayoutAttributeBottom
                                          relatedBy:NSLayoutRelationEqual
                                             toItem:self
                                          attribute:NSLayoutAttributeCenterY
                                         multiplier:1
                                           constant:0];
[self addConstraints:@[titleLabelBottom]];

so, you can use titleLabelBottom anywhere in class.

hope this will help :)




回答2:


You are getting nil because the constraint has not been created yet.

Try logging your constraints in:

- (void)viewDidLayoutSubviews;

Assumming that constraint is essential to your CustomView, you should create that constraint in your initWithFrame method method.



来源:https://stackoverflow.com/questions/36641487/how-to-get-constraints-from-uiview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!