Small Category on UIView for Programmatic Auto Layout

Save one line of code.


Lately, I’ve found myself using Auto Layout programmatically quite often. Each time I instantiate a new UIView object to be manipulated through Auto Layout, I forget to set this boolean property:

[view setTranslatesAutoresizingMaskIntoConstraints:NO];

Therefore, I’ve made a small category on UIView that does it for me! Whenever I need to create a new UIView or subclassed UIView object I simply call this simple initializer:

[UIView autoLayoutNew] // For a UIView object 
[MyView autoLayoutNew] // MyView is a sub-classed UIView object

The category is called UIView+AutoLayoutView, and contains only one class method:

+ (instancetype)newAutoLayoutView
{
UIView *view = [[self alloc] init];
[view setTranslatesAutoresizingMaskIntoConstraints:NO];

return view;
}

It only saves one line of code, but it gives me piece of mind that I automatically have a programmatic Auto Layout compliant object.