August 20, 2021

Property Wrapper for Autolayout

Property wrappers is very convenient mechanism for property implementation patterns that come up repeatedly. It firstly appeared in the SE-0258. For example, I made a simple wrapper to automatically set translatesAutoresizingMaskIntoConstraints to false for our UI objects.

@propertyWrapper
struct Autolayout<View: UIView> {
    var wrappedValue: View

    init(wrappedValue: View) {
        self.wrappedValue = wrappedValue

        setUpView()
    }

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

// Example of usage
final class MyView: UIView {
    @Autolayout private let label = UILabel()
    
    // ...
}