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
?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With