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

Search for a command to run...

No comments yet. Be the first to comment.
Mandates, not just deprecations.

While working on large git-enabled projects in teams, merge conflicts can be the biggest nightmare and quite a challenging task, and my team is not exempt from this challenge. The Problem The case for Xcode projects regarding merge conflicts is quite...

Coming in Swift 5.9, package will be a new access modifier in the language. The Swift team at Apple approved the Swift Evaluation proposal SE-0386 which includes adding a new access modifier called package to allow symbols from being accessed inside ...

In case you really care about your apps' security.

Life is full of excitement and surprises, so does whatever journey you're in. During my iOS development journey, I have learned so much exciting stuff that I am always glad to get to know them. So, I would like to share them with you. It doesn't matt...

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.