Jim Kubicek

Octo-Impressive

Abusing UIView

Sometimes I long for the day when I get to create an iOS app that just uses Apple’s default interface element. Of course, this doesn’t last long, because using and abusing UIView is fun. Over the years I’ve picked up a few tips and tricks for making the most out of your time. The best tip is, first and foremost, you need to start copying Apple.

This cannot be emphasized enough. Apple’s framework developers aren’t perfect and they have made mistakes, but overall they provide excellent frameworks, especially for UI development. Make your class interfaces look like Apple’s class interfaces. Try to subclass Apple’s own elements before going off and creating your own. Don’t reinvent the wheel.

That being said, any iOS app of a decent size will create many custom UIView subclasses and learning how to properly subclassing UIView will reap benefits.

  1. You’ll get a lot of useful behavior right out of the box.
  2. You increase readability of your code and make it easier for future developers to understand what you’ve written.

Here are some tips for abusing UIView

Subclass the right class

If you are creating a generic control, subclass UIControl. If you are creating a custom button, subclass UIButton (or just create a custom button! That’s usually all you need). If you are creating a custom switch, subclass UISwitch (lols, just kidding. UISwitch is a terrible and fragile class to subclass. Write your own switch if you need something custom).

I see so many developers implementing complex touch event listeners in their UIView subclasses or a needless delegate protocol when they could have just gotten the same behavior for free by using the proper superclass.

Use UIViewAutoResizingMask

Your first attempt at custom layouts should always use UIViewAutoResizingMask (this changes in iOS 6.0, read more on developer.apple.com). Setting these up takes a trivial amount of time and you stand a pretty good chance of eliminating your custom layout code. Writing flexible and extensible layout code is very hard, which is why most developers don’t bother and just hard-code a bunch of magic numbers into their view layouts. Your layout may always be 320px wide today, but someday you’re going to enable landscape orientation in your app and having to go back in and debug your layout all over again is going to be a major headache.

Override layoutSubviews

Realistically speaking, you’re probably going to have layouts that springs and struts can’t handle. If you need to do custom layouts, do them in the correct location, by overriding layoutSubviews. You should always put your layout code in this method. Here’s some great reasons why you should be doing this.

  1. layoutSubviews will only be called once per run-loop. You can call [self setNeedsLayout] as much as you want without worrying about taking a performance hit laying out your views needlessly.
  2. layoutSubviews is common knowledge. Other developers (and yourself in 6 months) should know to look here for layout code. No need to try and scan unfamiliar code to find the method doing layout; it’s always the same one.
  3. Putting all your layout in one method makes handling state changes much more robust. Big Nerd Ranch has a writeup you should read.

It’s fairly common to have your layout depend on the properties of your subviews. This is how people tend to handle layout and it’s wrong.

1
2
3
4
5
6
7
8
9
10
11
12
- (void)setDeleteButtonVisible:(BOOL)visible {
  if (visible == _visible) return;

  _visible = visible;

  if (visible) {
      // move some stuff around to make room for this button
  } else {
      // move stuff around to cover the empty space
      // where the delete button was
  }
}

The biggest issue with doing this is that it scatters your layout code all over your class. Once you get two, three, four or more properties that influence your layout, each property setter becomes an incomprehensible mess of layout code. Don’t do this. A much better way to handle property-based layouts is to override layoutSubviews.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)setDeleteButtonHidden:(BOOL)hidden {
  if (hidden == self.deleteButton.hidden) return;

  self.deleteButton.hidden = hidden;
  [self setNeedsLayout];
}

- (void)layoutSubviews {
  [super layoutSubviews];

  if (self.deleteButton.hidden) {
      // layout for hidden delete button
  } else {
      // layout for visible delete button
  }
}

You can feel free to call [self setNeedsLayout] as much as you want, those calls will be consolidated and the layout methods will only be called once per run loop. For complex layouts, this can be a massive performance win.

Override sizeThatFits:

- (CGSize)sizeThatFits:(CGSize)size is the unsung hero of custom UIView subclasses. This method can be used to set minimum sizes, maximum sizes, and optimal sizes. The trick here is that the UIView method sizeToFit calls through to sizeThatFits: with the current size, then resizes the view based on the response. sizeToFit: is always the method that you should override, it’s the designated initializer of sizing methods. A great use for this method is to allow users to initialize your class with a zero sized rect while still maintaining a proper frame.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
      [self sizeToFit];
  }
  return self;
}

- (CGSize)sizeThatFits:(CGSize)size {
  if (size.width  < kMinWidth)  size.width  = kMinWidth;
  if (size.height < kMinHeight) size.height = kMinHeight;

  return size;
}

Now, if someone really wants to initialize your view to an absurd size you can prevent this by overriding setFrame:, but in my experience, when someone resizes something to the wrong size, it’s obvious what they did wrong. When they’re attempting to resize something and it just won’t become the correct size, it’s usually a mystery why. Don’t surprise your users, let them shoot themselves in the foot, but make it obvious that they are shooting themselves in the foot.

Respond intelligently to weird frame sizes

If your UIView is instantiated by calling init, the default implementation will call through to initWithFrame: and pass CGRectZero. This is very common, and it shouldn’t cause your view to blow up or completely break. If you have a minimum size that your control should be, resize yourself in initWithFrame. If you don’t have a minimum size, make sure your subviews are pinned to the correct edges of your bounding rect so that they behave correctly when your view is resized. These two views should both have the same frame and be layed out identically:

1
2
3
4
CGRect frame; // Declared to be something reasonable
MyCustomView *view1 = [[MyCustomView alloc] initWithFrame:frame];
MyCustomView *view2 = [[MyCustomView alloc] init];
view2.frame = frame;

A UIView that blows up when instantied with a size zero frame is a perpetual source of developer annoyance. Don’t do this. If you need to use default frame sizes, provide an initializer that doesn’t take a frame as a parameter, and override initWithFrame: to ignore the input frame size. Make a note in the documentation to this effect.

Override pointInside:withEvent:

The default behavior of pointInside:withEvent: returns YES if the point is within your bounds. Override this method if your shape does not completely fill its bounds. For example, if you have a button with a transparent center region, you may not want to respond to taps in that region. Override this method to return NO for any points within that transparent area.

Even more useful, if you have a control that is smaller than the Apple HIG recommended guidelines of 44x44px, you can respond to touches outside your bounds, effectively increasing the tap target for a given button.

Don’t override drawRect:

Overriding drawRect: causes a performance hit. I haven’t profiled it, so I don’t know if it’s a signifigant performance under normal circumstances (it’s probably not), but in most cases, folks who override drawRect: can accomplish what they want much easier by setting properties on a view’s layer property. If you need to draw an outline around a view, here’s how you would do it:

1
2
3
4
5
6
7
8
9
#import <QuartzCore/QuartzCore.h>

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
      self.layer.borderWidth = 2.f;
      self.layer.borderColor = [UIColor redColor].CGColor;
  }
  return self;

TL;DR

Learning how to properly subclass UIView will save you a lot of coding, a lot of debugging and will make it much easier for future maintainers of your code to read and understand what you’ve done, arguably the most important consideration for a developer.

Sensational.ist

This is my million dollar idea. The idea is called “Sensational.ist”. Install an extension in your browser. Whenever you read a news article that is full of sensationalist nonsense, trigger the extension. If enough people have labeled an article as sensationalist, all new visiters will see a warning page.

Caution: This article is complete bullshit.

This article was likely written with a goal of being confrontational to drum up pageviews and advertising dollars. By visiting this site you are supporting the fucks that are ruining online journalism. Please don’t visit this page. Rest assured that whatever meager content that was there is utter nonsense and by avoiding it you are helping to get that ass goblin fired.

Sort Obj-C Methods With Automator

Big view controllers in big projects tend to accumulate a lot of private methods and properties. In a perfect world, these methods and properties should be carefully organized into functional groups and carefully documented. In the world we actually live in, that shit doesn’t happen, which is why I’ve resigned myself to organizing everything alphabetically.

To make my life easier, I created an automator service that sorts everything for me. Here’s how you create it yourself:

  1. Open Automator.app
  2. Create a new workflow and select “Service”
  3. Drag the “Run Shell Script” workflow into the workflow pane.
  4. Above the workflow, change the drop downs to read “Service recives selected text in Xcode” and check the “Output replaces selected text” box.
  5. Change the shell drop down to “/usr/bin/ruby”
  6. Paste the gist below into the text view.
  7. Save the service with an appropriate name and you’re done!

Keep in mind that any comments need to be inline and all method names need to be on one line, no splitting accross multiple lines. I’m not too concerned about this, as it fits my style (I have word wrap turned on) and since nobody ever reads comments on declarations in the .m file anyway. When I get a chance I’d like to update this to clean up property declarations (all the names at the same tab-stop) and remove extraneous spacing in method declarations.

Open Sourcing? Eliminate All Warnings

A few months ago Matt Gemmell created a fantastic writeup on creating open-source components. One salient point he missed, though, is that you must compile and test your code with the strictest warnings available. You never know who’s going to be using your code and what warnings they have enabled. Assume the worst, and turn on nearly every warning you can in your project. Peter Hosey’s list is a great start (there’s even some AppleScript to automate turning on all these warnings). If you’d like to be extra cautious, use the -Weverything flag in Clang to turn on all the warnings.

Having Trouble With Adium and iMessage?

I exclusively use Apple’s iMessage for chat. Most of my coworkers use Adium. Ever since I started this job there have been weird issues were coworkers can’t see me online and don’t respond when I message them. I’ve confirmed that they are not actually getting the messages (and they aren’t quietly hellbanning me).

Also, the name of my lapop is the Emoji characters 🐒💨.

Also, your default location in iMessage is the name of your computer.

Turns out there’s a bug in either iMessage, Google Chat or Adium (probably Adium, since iMessage <-> Google Chat works just fine) where Emoji characters in your location cause you to not be visible in Adium. I changed my location to something more vanilla and now all my coworkers can see me online. Hooray!

Configure Git to Only Push Current Branch

I’ve always used plain git push to update my remote repos and I’m finally getting tired of seeing this error every time:

(master)> git push
...
To git@github.com:jkubicek/my_proj.git
   21b430d..dd378ca  master -> master
 ! [rejected]        release -> release (non-fast-forward)
error: failed to push some refs to 'git@github.com:jkubicek/my_proj.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. If you did not intend to push that branch, you may want to
hint: specify branches to push or set the 'push.default' configuration
hint: variable to 'current' or 'upstream' to push only the current branch.

I can only blame this on my utter laziness, because the answer is right in the error text. Run the following command to configure git push to only push your current branch.

git config --global push.default current

I should have done this months ago.

Don’t Lazily Load Your Views

I seem to run accross a lot of developers lazily loading their properties. As an example:

- (UILabel *)myTextLabel {
     if (_myTextLabel == nil) {
         _myTextLabel = [[UILabel alloc] init];
         [self addSubview:_myTextLabel];
     }
 }

At least in iOS developement, I suspect this is caused by Apple’s sample code, particularly Apple’s default setup for Core Data projects. There are some valid reasons why you’d want to lazily load a resources, but there’s lots of great reasons why you shouldn’t. Here’s a few:

Property calls should not have side effects

There are lots of exceptions for setters (like updating the UI after setting a property), but there are very few exceptions for getters. You shouldn’t need to worry about your object changing state when you access a property.

Lazy loading is confusing

self.myTextLabel = nil;
if (self.myTextLabel) {
 NSLog(@"What the shit? How did I get here?");
}

Lazy loading leads to tricky initialization order dependences

- (UILabel *)myTextLabel {
    if (_myTextLabel == nil) {
        _myTextLabel = [[UILabel alloc] init];
        _myTextLabel.text = self.myTitle;
        [_myTextLabel sizeToFit];
        [self addSubview:_myTextLabel];
    }
}

Now your label will have different text depending on whether you set myTitle before or after you access myTextLabel.

Lazy loading leads weird code

Like this:

if(self.myTextLabel) // just need to setup my text label

Initialization, layout, UI updates should be localized

You should be performing all initialization in the init method, UI updates in an update UI method and layout in layoutSubviews. Not only does this make debugging far easier (having layout issues? I feel bad for you, son. I’ve got 99 problems, but performing view layout anywhere other than layoutSubviews isn’t one.), but it ensures that your view is always in a consistent state. Big Nerd Ranch has a great writeup on why this is important.

Clearly there are exceptions to all these rules and situations where lazily loading your view properties is the right thing to do. But remember, always write code that emphasizes clarity first and optimize for speed or memory constraints later.

OK. For Serious This Time

OK. This is a fresh start. I think I’ve got this blogging thing figured out for once. I’m using Octopress to create the site. I attempted to install Octopress a few months ago, but ran into a whole host issues trying to get ruby 1.9.2 to build. Luckily, Ruby 1.9.3 seems to fix all my issues, and installed smooth as silk. I never really got a chance to use Octopress 1.x, but 2.0 is going great. Here’s what I wanted in a blogging platform.

  1. Pre-rendered HTML pages I don’t have any illusions about the amount of traffic I’ll be getting, so performance isn’t that a concern for me. I do want to avoid the “black box” of PHP and MySQL that I’d been used to with Wordpress. The chances of me learning every little detail of the blogging platform are slim, but if I do decide to dive in, I want it to be as easy and as frictionless as possible. Octopress is just a bunch of scripts. Nothing sneaky there!

  2. Easy to modify A little bit of HTML, a bit of javascript, maybe a little ruby. Writing themes and modifying the behavior of the site is something well within my reach.

  3. Run the site locally Right out of the box, Octopress makes it easy to get a full version of your site served locally. Try that, Wordpress!

  4. Text only input I want to be able to write a blog post from anywhere on any device. Having plain text input ensures that I’ll have no excuses if I want to get something written. Plus, if I need to search my entries or make bulk changes, I’ve got my command line tools right here. Oh, and shit, I can also sit in coffee shops running full-screen Vim (green text on black background) to look like an über-hacker.

  5. Good code formatting I’d like to make this a mostly develpment blog. Good code formatting is important. Easy code formatting is just as important.

Most importantly, I’ve got a pretty sizeable chunck of writing saved up and ready to deploy. I’m hoping I can just throw these files in my favorite text editor and hit “publish”. I’m sure a few will get thrown out in the editing process, but I’m hoping that I use those first few posts to build up some intertia.

Let’s see where this takes us!