Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I subclass a UIButton?

I've asked a few questions on stack overflow about subclassing a UIButton, and a couple of people have informed me that I shouldn't subclass a UIButton.

What are the negatives of subclassing a UIButton? And I know it's vague, but what are other alternatives to subclassing a UIButton?

like image 374
SirRupertIII Avatar asked Nov 02 '12 19:11

SirRupertIII


People also ask

Should I subclass UIButton?

Don't subclass UIKit controls (e.g. UIButton , UILabel , UITextField and UISlider ). UIKit is built on composition, and this fact is reflected throughout its API.


1 Answers

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 
like image 120
Chris Trahey Avatar answered Sep 22 '22 01:09

Chris Trahey