Why shouldn’t I subclass a UIButton?

The Cocoa frameworks take the approach that the Object Composition pattern is more appropriate than traditional class hierarchy.

In general, this means that there is likely to be a property on UIButton where you can set another object to handle various aspects of the button. This is the preferred way to “customize” how your button works.

One of the main reasons for this pattern is that many library components create buttons and don’t know that you want them to create instances of your subclass.

edit, your own factory method

I noticed your comment above about saving time when you have the same button config across many buttons in your app. This is a great time to use the Factory Method design pattern, and in Objective-C you can implement it with a Category so it’s available directly on UIButton.

@interface UIButton ( MyCompanyFactory )
+(UIButton *) buttonWithMyCompanyStyles;
@end
@implementation UIButton
+(UIButton *) buttonWithMyCompanyStyles {
    UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
    // [theButton set...
    return theButton;
}
@end

Leave a Comment