objective-c - 为什么我不应该子类化 UIButton?

标签 objective-c ios uibutton uikit subclass

我问了几个关于子类化 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/

相关文章:

ios - iOS 上的 DST 独立时间

ios - ObjC 将文本文件行添加到 PickerView

iphone - 努力以正确的方式命名此方法

ios - 一些 uitableviewcell 在我滚动 iPhone 之前不会显示所有数据

javascript - react native 路由器通量: Nested router in components

ios - 如何将 3 个 UIButton 对齐到 UITableCellView 的中心?

uiview - 如何使 UIbutton 在 UIView 中可拖动?

ios - UIBarButtonItem 设计更改第一次不起作用,但第二次不起作用

ios - 在 Interface Builder 中使用泛型类作为自定义 View

ios - UIButton 突然停止工作