I had a rough battle with AutoLayout these days1. The following notes are in the context of a
UITableView with dynamic sizing cells. :
- If you want to change an
layoutMargins, don't use Interface Builder. After some time tracking this down, it seems that if you set
contentView's "Explicit Margins" to
(0,0,0,0)it will just disregard it and use the default ones which are
(8,8,8,8). For whatever reasons, setting it to
(1,1,1,1)actually works. The workaround can be placed in the cell's
self.contentView.layoutMargins = UIEdgeInsetsMake(10,5,5,10)).
- While adding constraints, don't tick off the "Constrains to margins". If you do and later you want to change the
layoutMargins, it won't have the outcome you would expect.
- If you are using an
heightI would recommend using this approach. My initial idea, was using an
heightconstraint and then in the code I would change it to the desirable value. For some reason, it didn't work (I believe the failure is from my side as I might have missed something).
- If you know the
sizeof the image, pass it to the cell between its creation (
dequeueReusableCellWithIdentifier) and its return from
cellForRowAtIndexPath. After setting it, call
self.layoutIfNeeded(). Otherwise the new height won't be considered and you will see the height you have set in InterfaceBuilder. Still, the height is applied (the same
UITableViewCellwhen recycled, will come with the correct one)
- I set the
contentView's "Explicit margin" to
(0,0,0,0), it seems that sometimes Xcode will revert it back to "Default". When this happens, you will get a constraints's warning (this is normal, since the constraints were added with the margin to
(0,0,0,0), or to whatever value you have use). I would just update it to Explicit again, but it's up to you.
- AutoLayout is extremely picky with the constraints you set, so I would recommend adding the bare minimum in order for it to work, if you see a warning on the debugger, make sure to fix it!
- Don't forget when adding constraints to your Views to make sure they go from top to bottom, left to right, otherwise the dynamic sizing won't be able to figure out the right size (this tutorial is awesome if you are starting).