When should translatesAutoresizingMaskIntoConstraints be set to true?

35,730

Solution 1

translatesAutoresizingMaskIntoConstraints needs to be set to false when:

  1. You Create a UIView-based object in code (Storyboard/NIB will set it for you if the file has autolayout enabled),
  2. And you want to use auto layout for this view rather than frame-based layout,
  3. And the view will be added to a view hierarchy that is using auto layout.

In this case not all of these are true. Specifically, point 2.

After you return the header view from viewForHeaderInSection it is added to the table view and its frame is set based on the current width of the table view and the height you return from heightForHeaderInSection.

You can add subviews to the root header view (header in your code) and use constraints to layout those subviews relative to the header view.

You have discovered the reason why you can't use autolayout for the header view itself in your comments; at the time you create the view it isn't yet part of the view hierarchy and so you cannot constrain its edges to anything.

In order to have dynamic header sizing, you will need to add subviews to your header view and add constraints between those subviews and header. Then, auto layout can use the intrinsic content size of header to determine the header view size.

Since you are not constraining the frame of header, do not set translatesAutoresizingMaskIntoConstraints to false. You will need to ensure that you have sufficient constraints on your subviews for auto layout to determine the size of header.

You will need a continuous line of constraints from top to bottom and potentially some height constraints for your subviews if the intrinsic content size of that subview is not sufficient.

Any subviews you add to header do need translatesAutoresizingMaskIntoConstraints set to false

You also need to return something from estimatedHeightForHeaderInSection - the closer to your actual header height the better - if you are using tableview.sectionHeaderHeight = UITableViewAutomaticDimension

Solution 2

  • For programmatically created view default is true and for views from Interface Builder default is false

    If the property is (or set to) True, the system automatically creates a set of constraints based on the view’s frame and its autoresizing mask. And if you add your own constraints, they inevitably conflict with the autogenerated constraints. This creates an unsatisfiable layout. So When programmatically instantiating views, be sure to set their translatesAutoresizingMaskIntoConstraints property to NO.

Solution 3

With PANKAJ VERMA's answer, it finally makes sense.

In my case, I have an ImageView and only set 2 constraints, yet the error shows that I have more constraints and LayoutConstraints was Unable to simultaneously satisfy constraints:

        view.addSubview(imageView)
        let yConstraint = imageView.centerYAnchor.constraint(equalTo: layout.centerYAnchor)
        yConstraint.identifier = "yConstraint"
        let xConstraint = imageView.centerXAnchor.constraint(equalTo: layout.centerXAnchor)
        xConstraint.identifier = "xConstraint"

Error message:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x600000089360 h=--& v=--& UIImageView:0x7fc1782087b0.minY == 0   (active, names: '|':UIView:0x7fc176406220 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x600000089220 h=--& v=--& UIImageView:0x7fc1782087b0.height == 0   (active)>",
    "<NSLayoutConstraint:0x600000088c30 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x600001a880e0'UIViewLayoutMarginsGuide']-(34)-|   (active, names: '|':UIView:0x7fc176406220 )>",
    "<NSLayoutConstraint:0x600000088cd0 'UIView-topMargin-guide-constraint' V:|-(48)-[UILayoutGuide:0x600001a880e0'UIViewLayoutMarginsGuide']   (active, names: '|':UIView:0x7fc176406220 )>",
    "<NSLayoutConstraint:0x600000088d70 'yConstraint' UIImageView:0x7fc1782087b0.centerY == UILayoutGuide:0x600001a880e0'UIViewLayoutMarginsGuide'.centerY   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600000088d70 'yConstraint' UIImageView:0x7fc1782087b0.centerY == UILayoutGuide:0x600001a880e0'UIViewLayoutMarginsGuide'.centerY   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

There was basically an almost identical error log for the 2nd constraint ("xConstraint") I set. As you can see in the error logs, I am "over-constraining" my UI. Along with 'yConstraint', I also have 4 other constraints. I believe the constraints are in a tuple, hence the paranthesis around them. XCode tries to be helpful by hinting "(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)", but personally I don't think this is helpful enough.


What is "Autoresizing Mask"?

I guess its important to know what this means, as this is being converted to constraints, hence the name translatesAutoresizingMaskIntoConstraints. Its an instance property of UIView containing an integer bit mask. It holds onto bits that you can toggle on and off for features like "flexible left margin" and "flexible height" (more of them here).

When a view’s bounds change, that view automatically resizes its subviews according to each subview’s autoresizing mask.

source

So to summarize the Autoresizing Mask, it holds onto the autoresize features you want, like flexible height and width.

Share:
35,730
mfaani
Author by

mfaani

I previously went by the user name Honey. I've now changed my profile name to mfaani. Please reach out if you have an interesting opportunity @mfaani. Also check out my blog at mfaani.com Check out my Developer Story for the posts I think are more unique

Updated on July 08, 2022

Comments

  • mfaani
    mfaani almost 2 years

    I've read the documentation. But I'm still not sure when I need to not set it to false. In the code below if I set it to false I won't see the header at all. If I leave it as true, then everything is fine.

    The following in View debug hierarchy will give a warning "width and position are ambiguous".

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        let header = UIView()
        header.translatesAutoresizingMaskIntoConstraints = false
        header.backgroundColor = .orange
        header.heightAnchor.constraint(equalToConstant: 10).isActive = true
    
        return header
    }
    

    I thought whenever I need to modify anything in the code I would have to set translatesAutoresizingMaskIntoConstraints to false.

    Perhaps it's more correct to say if you need to remove all its constraints then set it to false and then add what you like, and in that case you would need to add constraints for all 4 sides.

    However, if you need to just keep what the system provides to you, in this case that would be the tableView managing its position and width then leave to true.

    Is that right?