Why shouldn't I subclass a UIButton? Why shouldn't I subclass a UIButton? ios ios

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


It's because UIButton is kind of special in that there are a few complexities/subtleties/restrictions (i.e. additional overrides for you to define, notably +buttonWithType:) required in order for it to work as expected. It's more than the usual -initWithFrame: (and -initWithCoder:, if used in XIBs). IDK why the framework authors allowed those details to leak out into our domain, but it's something that must be dealt with by us now. The restriction is that your implementation must not depend on (i.e. extend) preset system button styles; You must assume UIButtonTypeCustom as your starting point for a UIButton subclass.


On implementing a subclass of UIButton


If you are just looking for something more lightweight with your own 'subviews' you should instead be subclassing UIControl. UIButton subclasses UIControl and can handle events, like:

[mySubclassedButtonFromUIControl addTarget:self action:@selector(_doSomething:) forControlEvents:UIControlEventTouchUpInside];

UIControl subclasses UIView so you can cleanly layoutSubviews on any views contained by your UIControl subclass and avoid unnecessary views that come with UIButton. In essence you are just creating your own 'UIButton' but you avoid having to work around behavior and functionality you don't really want or need.