King T. King T. - 21 hours ago 2
iOS Question

Autolayout not working on centerX- centerY

I am trying to add constraint manually; I am having the following error every time the code tries to add the centerX and centerY constraints:


Terminating app due to uncaught exception 'NSGenericException',
reason: 'Unable to install constraint on view. Does the constraint
reference something from outside the subtree of the view? That's
illegal. constraint:
(active)> view:>'



I checked multiple questions from before but nothing helped :/

Thank you!My code[1]

CODE

[cell.contentView addSubview:imageView];
[cell.contentView addSubview:title];
title.translatesAutoresizingMaskIntoConstraints = NO;
imageView.translatesAutoresizingMaskIntoConstraints = NO;


NSLayoutConstraint *imageViewHeightConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:[UIScreen mainScreen].bounds.size.width/8];
NSLayoutConstraint *imageViewWidthtConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:imageView
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0];
NSLayoutConstraint *imageViewCenterXConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:[imageView superview]
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];

NSLayoutConstraint *imageViewCenterYConstraint = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:[imageView superview]
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[imageView addConstraint:imageViewHeightConstraint];
[imageView addConstraint:imageViewWidthtConstraint];
[imageView addConstraint:imageViewCenterXConstraint];
[imageView addConstraint:imageViewCenterYConstraint];

Answer

Remove the addConstraint lines and add .active = YES after each instantiation of the constraint. Also change [image superview] for cell