Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get constraints from UIView Programmatically

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
like image 642
Jesse Avatar asked Apr 15 '16 08:04

Jesse


2 Answers

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 :)

like image 194
Ketan Parmar Avatar answered Oct 13 '22 21:10

Ketan Parmar


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.

like image 44
facumenzella Avatar answered Oct 13 '22 23:10

facumenzella