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
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With