Search code examples
iosuikit

How does "translatesAutoresizingMaskIntoConstraints" actually work?


I've recently taken up trying to learn how to create iOS applications completely programatically. And due to this, one of the first roadblocks I've encountered is that translatesAutoresizingMaskIntoConstraints must usually be set to false in order to set constraints.

After doing some research, there are three things that I am pretty sure of.

  1. AutoresizingMasks are how dynamic layouts (layouts that differ based on screen size/orientation) were achieved prior to the introduction of the auto-layout system.
  2. AutoresizingMasks are a value that tell a view's superview how to resize it when the superview's bounds change.
  3. translatesAutoresizingMaskIntoConstraints is a boolean value that when set to true (and is always defaulted to true for code-created UIViews), tells the UIKit framework to create constraints that replicate the behavior of the AutoresizingMask property within the auto-layout system.

What I don't understand is how exactly these constraints are implemented. Apple states in their documentation that "the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties..."

This is the part that confuses me, and I'm not sure if it's just their wording or my misunderstanding of the topic. The AutoresizingMask is just a value, so it doesn't make sense to be able to create constraints off of it. Do they mean that the automatically generated constraints are actually based off the child view's frame (A.K.A. childView.topAnchor = superview.topAnchor)? and that the AutoresizingMask's value just determines which of these constraints based on the frame gets set?

For example: UIView with frame of (x:0, y:0, width:50, height:50) and AutoresizingMask of "FlexibleBottomMargin". Does UIKit just automatically create constraints that place the view where a frame-based layout would have, and then leave out certain constraints (in this case the bottom) to replicate the mask's behavior?


Solution

  • You are correct that the autoresizingMask is interpreted (along with the frame) to determine which constraints to create.

    In the example you give the system would create the following constraints -

    • Width constraint of 50
    • Height constraint of 50
    • Leading, trailing and top constraints to the nearest neighbours, with the fixed distance to those neighbours
    • Greater than or equal bottom constraint to the nearest neighbour with the distance to that neighbour.

    This would result in a 50x50 view that was fixed horizontally and at the top and where the space between the bottom and its neighbour can grow as required.