A convenient way of enabling Auto Layout for UIView in Swift 5

Sometimes we want to enable Auto Layout when you are creating a UIView in code. We can make that process a lot easier with a simple extension.

This extension will initialize a UIView that sets translatesAutoresizingMaskIntoConstraints to the opposite of useAutolayout from the initializer and thus enables the view for Auto Layout if useAutolayout is true:

extension UIView {
    convenience init(useAutolayout: Bool) {
        translatesAutoresizingMaskIntoConstraints = !useAutolayout

Now we can use it like this in our code:

let view = UIView(useAutolayout: true)