Makwan Barzan
Makwan's Blog

Follow

Makwan's Blog

Follow
Swift: A Custom Property Wrapper For Disabling Views' Auto Resizing Mask Into Constraints

Swift: A Custom Property Wrapper For Disabling Views' Auto Resizing Mask Into Constraints

Makwan Barzan's photo
Makwan Barzan
ยทOct 6, 2022ยท

2 min read

Play this article

Have you ever spent hours investigating your code to see why your UI implementation is crashing because you forgot to disable translatesAutoresizingMaskIntoConstraints? Well, because I did, and I know how depressed and hurtful it feels.

In this article, I will introduce you to a custom property wrapper which can save you so much time in the future. Because you no longer need to disable views' auto-resizing ask manually.

But first, know what a property wrapper in Swift is:

A property wrapper adds a layer of separation between the code that manages how a property is stored and the code that defines a property.

Now, time to show off the custom property wrapper.

Create a new Swift file. Feel free to name it anything, but for the article I name it AutoLayoutUsage, the same as the property wrapper's name.

import class UIKit.UIView

@propertyWrapper
public struct AutoLayoutUsage<T: UIView> {
    public var wrappedValue: T {
        didSet {
            setTranslatesAutoresizingMaskIntoConstraints()
        }
    }

    public init(wrappedValue: T) {
        self.wrappedValue = wrappedValue
        setTranslatesAutoresizingMaskIntoConstraints()
    }

    private func setTranslatesAutoresizingMaskIntoConstraints() {
        wrappedValue.translatesAutoresizingMaskIntoConstraints = false
    }
}

You may wonder if I only imported the UIView class only from UIKit. It's because I want to reduce the API surface of the file. You're welcome.

Here is a usage example of the property wrapper for the view components:

import UIKit

final class SomeView: UIView {
    // ...

    @AutoLayoutUsage var button = UIButton()

    // ...
}

All you need is to write down @AutoLayoutUsage before declaring component variables. You are no longer required to write $0.translatesAutoresizingMaskIntoConstraints = false manually!

Please don't forget that you must create variables for your components rather than constants because property wrappers only support variables.

That was it! I hope it saves you from seeing your views crash before getting initialised.

ย 
Share this