我问了几个关于子类化 UIButton
的堆栈溢出问题,一些人告诉我我不应该子类化 UIButton
。
UIButton
的子类化有哪些负面影响?我知道这很含糊,但是除了子类化 UIButton
之外还有哪些替代方法?
最佳答案
Cocoa 框架采用对象组合模式比传统类层次结构更合适的方法。
一般来说,这意味着 UIButton 上可能有一个属性,您可以在其中设置另一个对象来处理按钮的各个方面。这是“自定义”按钮工作方式的首选方式。
这种模式的一个主要原因是许多库组件创建按钮并且不知道您希望它们创建您的子类的实例。
编辑,你自己的工厂方法
我注意到您上面关于当您在应用程序中的多个按钮上使用相同的按钮配置时节省时间的评论。现在是使用工厂方法设计模式的好时机,在 Objective-C 中您可以 implement it with a Category所以它可以直接在 UIButton 上使用。
@interface UIButton ( MyCompanyFactory )
+(UIButton *) buttonWithMyCompanyStyles;
@end
@implementation UIButton
+(UIButton *) buttonWithMyCompanyStyles {
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
// [theButton set...
return theButton;
}
@end
关于objective-c - 为什么我不应该子类化 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202161/