Search code examples
iosswiftuitableviewuikitconstraints

Setting translatesAutoresizingMaskIntoConstraints to all subviews


Anybody know the implications of setting translatesAutoresizingMaskIntoConstraints to false for all subviews?

Consider the following:

extension UIView {
    public func setAutoresizingMaskIntoConstraintsForAllSubviews() {
        for v in self.subviews {
            v.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}
...
let cell = UITableViewCell()
cell.setAutoresizingMaskIntoConstraintsForAllSubviews() //or
cell.contentView.setAutoresizingMaskIntoConstraintsForAllSubviews()

Based on my tests everything works. I don't see any constraint conflict with any UIKit component.

Per Apple's docs:

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

https://developer.apple.com/reference/uikit/uiview/1622572-translatesautoresizingmaskintoco


Solution

  • While there may not be anything inherently wrong with that...

    First, that won't hit subviews of subviews, unless you make it recursive.

    Second, if you do make it recursive, you'll end up setting properties of things like scrollview scroll indicators, button background image views, etc.

    Third, since you are doing this because you are creating the views programmatically, why aren't you explicitly setting the value in that code?

    And, in general, just blindly throwing a "catch-all" piece of code at something because you're not sure what's going on is a pretty bad idea.