为什么我不应该继承 UIButton? [英] Why shouldn't I subclass a UIButton?

查看:45
本文介绍了为什么我不应该继承 UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了几个关于子类化 UIButton 的堆栈溢出问题,有几个人告诉我我不应该子类化 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.

子类化 UIButton 的缺点是什么?而且我知道这很模糊,但是除了子类化 UIButton 之外还有哪些其他选择?

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

推荐答案

Cocoa 框架采用的方法是对象组合模式比传统的类层次结构更合适.

The Cocoa frameworks take the approach that the Object Composition pattern is more appropriate than traditional class hierarchy.

一般来说,这意味着 UIButton 上可能有一个属性,您可以在其中设置另一个对象来处理按钮的各个方面.这是定制"的首选方式.你的按钮是如何工作的.

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.

我注意到您在上面的评论中提到,当您的应用中的许多按钮具有相同的按钮配置时,可以节省时间.这是使用工厂方法设计模式的好时机,在 Objective-C 中你可以 使用 Category 实现它,以便它可以直接在 UIButton 上使用.

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

这篇关于为什么我不应该继承 UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆