Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint the CenterX of a view to be fraction of overall width of superview

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?

like image 381
Sullivan Avatar asked Jan 27 '26 05:01

Sullivan


2 Answers

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

enter image description here

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.

like image 127
NKorotkov Avatar answered Jan 29 '26 19:01

NKorotkov


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.

like image 44
rob mayoff Avatar answered Jan 29 '26 18:01

rob mayoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!