Thursday, December 4, 2014

A few more autolayout tips and tricks



1.  If you add an view to a container without specifying constraints to derive width/height  it will use the object's intrinsicContentSize.   This is nice if you want to maintain the aspect ratio of the view. 

2.  I have wasted many hours of my life that I'll never get back spent gobs of time attempting to mix IB Autolayout with programmatic constraints.  The problem is because IB automatically inserts its own constraints (thanks IB!) which then conflict with the ones that I'm trying to set (See #3 below).

Several StackOverflow posts recommend checking off the "Remove at build time" flag for constraints that should be set or adjusted programmatically.  That will work, but it means I'll always have to programmatically add that constraint - but sometimes the default IB constraint is fine until something else in the layout changes (e.g., a view is added or removed)

In that situation, just set the priority of the constraint in IB to "High" (vs "Required").  That way, if you add a constraint that conflicts with the default IB constraint, you won't get bad layouts or error messages.

3. Programmatically removing all of the IB built-in constraints for a given view seems to be beyond my technical abilities.  In some situations, no matter what I do, I just can't seem to get rid of those @#!$&$! default IB constraints.  See #2.

4. You can add the same constraint numerous times without error.  I'll leave it up to you to decide if that's a good thing

5. And so I don't forget,  here's how to position two views at 25% and 75% of parent width with programmatic constraints:

   [buttonPanel addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:buttonPanel attribute:NSLayoutAttributeCenterX multiplier:.5 constant:0]];

   [buttonPanel addConstraint:[NSLayoutConstraint constraintWithItem:button2 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:buttonPanel attribute:NSLayoutAttributeCenterX multiplier:1.5 constant:0]];

No comments:

Post a Comment