Dark star
Dark star

Reputation: 5852

Make translatesAutoresizingMaskIntoConstraints false when I added constraints

I make view programmatically and and when I want to add auto Layout to the view it’s painful to set translatesAutoresizingMaskIntoConstraints false every single time. Now I’m looking for any solution to make life easier. Is there any extension or class that make it disable every time I want to add constraints?

Thanks.

Upvotes: 0

Views: 1842

Answers (2)

Ratnesh Jain
Ratnesh Jain

Reputation: 681

You can extend UIView class for constraints so that it applies to all the UIControls and custom UIViews.

extension UIView {
    func anchor(_ anotherView: UIView) {
        anotherView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(anotherView)
        anotherView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        anotherView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        anotherView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        anotherView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    }
}

Example:

func setupView() {
    self.view.anchor(self.someImageView)
}

Upvotes: 0

Glenn Posadas
Glenn Posadas

Reputation: 13290

I'm thinking you could add that line translatesAutoresizingMaskIntoConstraints in your view subclass. For instance, you usually use UITextField, or say UIView, for sure you have such base classes, like so:

import UIKit

/// Another Customized/Subclassed UIButton.
class BaseButton: UIButton {

    /// override init
    override init(frame: CGRect) {
        super.init(frame: frame)

            self.translatesAutoresizingMaskIntoConstraints = false
       }
    }

    /// override coder
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Or better yet, may I suggest, this one below? I use SnapKit for all my production level projects.

https://github.com/SnapKit/SnapKit

I hope this helps!

Upvotes: 1

Related Questions