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


i constraint center of subview @ 1/6 of overall width of superview.

for example:

if superview's width = 6

centerx of subview = 1

i wrote following code in superview class (self), constraint centerx of asubview, , crashing:

// hits here  [nslayoutconstraint constraintwithitem:self.asubview                              attribute:nslayoutattributecenterx                                 toitem:self                              attribute:nslayoutattributewidth                             multiplier:1/6                               constant:0]; // crashes here 

is there way nslayoutconstraints @ all?

i have 2 ideas why might crashing:

1) self in context? sure it's uiview subclass?

2) 1/6 should result in 0, , not valid multiplier. try 1.0/6 instead

update:

method name

+ constraintwithitem:attribute:relatedby:toitem:attribute:multiplier:constant: 

where's relatedby: part in code?

update 2:

it seems it's not allowed after all. tried reproduce crash , logs following error:

invalid pairing of layout attributes

but! can use trailing instead of width achieve desired layout, holds same value actually, if superview's left side connected screen (see image understand better).

enter image description here

this tested , 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 add constraint superview of view want position.


Comments