xcode - Adding NSLayoutConstraint from code -
i having lot of problems understanding constraints made in code. have container view created , set in ib , in container nsview's initwithframe add child nsview (self container view):
childview = [[nsview alloc] initwithframe:cgrectmake(0, 0, self.frame.size.width, tabcontainerheight + tabcontainertopspace)]; [childview settranslatesautoresizingmaskintoconstraints:no]; [self addsubview:childview]; nslayoutconstraint *tabcontainerconstraint = [nslayoutconstraint constraintwithitem:childview attribute:nslayoutattributetop relatedby:nslayoutrelationequal toitem:self attribute:nslayoutattributetop multiplier:1.0f constant:0.0f]; [childview addconstraint:tabcontainerconstraint]; tabcontainerconstraint = [nslayoutconstraint constraintwithitem:childview attribute:nslayoutattributeleading relatedby:nslayoutrelationequal toitem:self attribute:nslayoutattributeleading multiplier:1.0f constant:0.0f]; [childview addconstraint:tabcontainerconstraint]; tabcontainerconstraint = [nslayoutconstraint constraintwithitem:childview attribute:nslayoutattributetrailing relatedby:nslayoutrelationequal toitem:self attribute:nslayoutattributetrailing multiplier:1.0f constant:0.0f]; [childview addconstraint:tabcontainerconstraint];
the problem right child view not visible @ all, don't know happens it. want have child view have top @ container view's top , same goes left , right, child view must have fixed height placed @ top of container view , stretch sides container view (like in attached image if explains it).
how done code?
thank you
søren
there few problems here.
first, you're using initwithframe:
, turning on autolayout - means frame information going discarded. need height constraint child view.
second, you're adding constraints child view instead of superview. autolayout system may able figure out constraints should added self
in case.
you can check frames of views in debugger or introspection tool reveal see things might going wrong - i'd guess in case have height of 0 in child view.
thirdly (this 1 isn't necessarily problem), code you're using unnecessarily verbose. individual creation format understand constraints making , complex cross-hierarchy constraints can leave ambiguous layouts or adding constraints wrong views. layout after suited using visual format language - 2 statements:
for horizontal layout:
@"|[childview]|"
for vertical layout:
@"v:|[childview(==height)]"
where height
either key in metrics dictionary, or replace hard coded height number.
i've written in tedious detail various ways create constraints in code: visual format language , individual constraints. these ios focused autolayout similar on both frameworks.
Comments
Post a Comment