How to get constraints from UIView Programmatically
10,705
Solution 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 :)
Solution 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.
Comments
-
Jesse almost 2 years
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
-
Vyachaslav Gerchicov about 7 yearsit returns the constraints which are placed inside this view only. For example if you have constraint
height = 0.5*superview.height
- you won't see it in this array