I would like to constraint the center of subview to be at 1/6 of the overall width of the superview.
For example:
If superview's width = 6
CenterX of subview = 1
I wrote the following code in the superview class (self), to constraint the centerX of aSubview, and it is crashing:
// Hits here
[NSLayoutConstraint constraintWithItem:self.aSubview
attribute:NSLayoutAttributeCenterX
toItem:self
attribute:NSLayoutAttributeWidth
multiplier:1/6
constant:0];
// Crashes here
Is there a way to do this with NSLayoutConstraints at all?
I have two ideas why this might be crashing:
1) what is self in this context? Are you sure it's a UIView subclass?
2) 1/6 should result in 0, and that is not a valid multiplier. Try 1.0/6 instead
UPDATE:
method name is
+ constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:
where's the relatedBy: part in your code?
UPDATE 2:
It seems it's not allowed after all. I tried to reproduce the crash and it logs the following error:
Invalid pairing of layout attributes
But! You can use Trailing instead of Width to achieve desired layout, it holds the same value actually, if the superview's left side is connected to the screen (see image to understand better).

This is tested and working:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.aView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1.0/2
constant:0];
[self.view addConstraint:constraint];
be sure to add your constraint to the superview of the view you want to position.
Create a spacer view. Set its hidden to YES. (Hidden views still participate in layout.) Pin the spacer's leading edge to the superview's leading edge. Constrain the spacer's width to be 1/6 of the superview's width.
Then constrain the “centered” view's center to the spacer view's trailing edge.
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