#2 Diary of a Secret App: AutoLayout

I had a rough battle with AutoLayout these days1. The following notes are in the context of a UITableView with dynamic sizing cells. :

  1. If you want to change an UITableViewCell's 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 awakeFromNib like (self.contentView.layoutMargins = UIEdgeInsetsMake(10,5,5,10)).
  2. 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.
  3. If you are using an UIImageView with variable height I would recommend using this approach. My initial idea, was using an IBOutlet to UIImageView's height constraint 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).
  4. If you know the size of 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 UITableViewCell when recycled, will come with the correct one)
  5. 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.
  6. 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!
  7. 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).
  1. Big thanks to my partner in crime Kristian Angyal. Without his help, this would take twice the time.