Amazement at Rookie Mistakes

I’m amazed by how much code I’ve seen written most likely by coders who are new to iOS that aren’t aware of this method:

- (void)layoutSubviews;

I’ve seen all sorts of weird ways that people try to position views, and all sorts of what look to be weird workarounds that are made simply because they must not have been aware of how layouting is done on iOS.

There is of course the old way where one can specify autoresizing masks. The new way is to use Autolayout. But at the end of the day, whenever you need to be sure a view is in a specific place, you can override layoutSubviews and make that happen.

- (void)layoutSubviews
   [super layoutSubviews];  // this is where autoresizing / autolayout is done

   // this is where you can be sure your elements will be where you want them to be.
   // i.e.  self.someButton.frame = CGRectMake(10, 62, 72, 44);

Then, whenever you need to make sure your views are in the right location (with the exception of an interface that is animating), you just call:

[self.someView setNeedsLayout];  

Now this gets into the deeper aspects of rendering. You call setNeedsLayout so that the next time the screen is drawn by iOS, you’ve marked this view as ‘dirty’. As a result, whenever you create a custom subview that has its own view hierarchy, it’s perfectly fine to instantiate them all with a frame of CGRectZero because if you specify where they should be in layoutSubviews, they get set there anyway. (THAT IS, IF you specify their frames in layoutSubviews)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s