【发布时间】:2014-02-06 18:20:45
【问题描述】:
3 个按钮,很多实现,在一个巨大的项目中。时髦的 Objective-c 程序员如何解决这个问题?
这更多是关于设计模式的问题,但我认为它是相关的,我正在努力寻找答案。
为了简化问题,假设我的应用程序中有 3 种按钮,我会经常使用它们。有VeryImportantButton、ImportantButton和NotVeryImportantButton,有不同的样式:边框、角、颜色等。
我不想到处复制粘贴
UIButton *mybutton = [[UIButton alloc] initWithFrame:frame];
[myButton setBackGroundColor:[UIColor redColor];
[myButton.layer setBorderWidth:2.0];
[…]
我可以看到三个解决方案:
1/ 子类化。这 3 个按钮将是 UIButton 的子类,参数将在实现文件中设置。这样我只需要分配初始化所需的按钮。
ImportantButton *mybutton = [[ImportantButton alloc] initWithFrame:frame];
2/ 一些辅助类(公共类方法、单例等)
UIButton *mybutton = [[UIButton alloc] initWithFrame:frame];
[ButtonImportantnessManager applyVeryImportantStyleToButton:myButton];
3/ 在 UIButton 上创建一个类别
#import "UIButton+Importantness.h"
UIButton *mybutton = [[UIButton alloc] initWithFrame:frame];
[myButton applyVeryImportantStyle];
我不知道其中一种解决方案是否比另一种更好,以及哪种解决方案更好。
目标是拥有一个可换肤的应用程序,因此 IB 仅用于布置 UI 元素,而不是设置样式。
我希望这对 SO 来说是一个有效的问题。感谢您的帮助。
【问题讨论】:
-
我在另一个答案中建议this method。
-
谢谢,这是一个很好的答案。你指的是什么 WWDC 会议?所以你会建议第二个响应,还是工厂模式的第四个?例如:
VeryImportantButton *myButton = [ButtonImportantnessManager buildVeryImportantButtonWithTitle:(NSString *)title];? -
该会话是从 2012 年开始的,它是 216:iOS 上的高级外观定制。我通常按照我建议的第一种方式来做,即在我的视图控制器中,抓住我的按钮并自己设置主题。除非我的大部分按钮都是以编程方式而不是在界面构建器中创建的,否则我通常不会采用工厂方式。 (顺便说一句,如果您喜欢我的其他答案,请点赞它和问题,以便其他人更容易找到它。)
标签: ios objective-c cocoa-touch cocoa-design-patterns