Swizzling UIView initializer with Autolayout

If you are a fan of autolayout and using it extensively, you can feel the pain of writing
self.translatesAutoresizingMaskIntoConstraints = NO;
every time UIView is initialized. This is awkward to use when I try to init UIView with following initializer,

UIView* v = [[UIView alloc] init];

It is implicit that I do not intent to use traditional frame structure. So why not set its autoresizingMaskIntoConstraints right after initialization?

So I added a swizzled method to set autoresizingMaskIntoConstraints off for newly created view. This is useful as I do not have to type redundant code every time new UIView is created.

However, if we want to create a UIView with initWithFrame initializer like below,

UIView* v = [[UIView alloc] initWithFrame:CGRectMake(0,0, 200, 100)];

its autoresizingMaskIntoConstraintsflag is Not set off, but user is expected to do so, as I assume that if user intended to provide frame in the initializer, he's probably not intending to use awesome autolayout features.

Here's how you can do it by creating category on UIView.

Let's call this category a UIView+JKAutolayoutEnabled and add the following code to swizzle the implementation.

- (instancetype)autoLayoutEnabled_init {
      self.translatesAutoresizingMaskIntoConstraints = NO;
      return [self autoLayoutEnabled_init];

+ (void)load {
     static dispatch_once_t once_token;  
     dispatch_once (&once_token, ^{
         SEL regularInitSelector = @selector (init);
         SEL customInitSelector = @selector (autoLayoutEnabled_init);  
         Method originalInitializer = class_getInstanceMethod (self, regularInitSelector);
         Method customInitializer = class_getInstanceMethod (self, customInitSelector);  
         method_exchangeImplementations (originalInitializer, customInitializer);

This is useful in the sense that it will save you from turning autoResizingMask off each time new view is created. However, beware of caveat that it may affect third party initializer too.

This was written with assumption that it user initializes UIView using [[UIView alloc] init] he wants to use the Auto Layout. However, if UIView is initialized using initWithFrame initializer, user does not want to use the Auto Layout and thus autoResizingMask needs to be turned off manually.

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!