使用单例来创建基本样式助手类 [英] Use of a singleton for creating a basic style helper class

查看:139
本文介绍了使用单例来创建基本样式助手类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是objective-c的新手,我有一个建筑或设计模式问题。我正在构建一个ios应用程序,像大多数ios应用程序一样,它使用各种颜色,字体,模式等。也许我目前正在编写错误的代码,但我发现自己重写了颜色设置等内容。结果,改变颜色成为查找代码中的所有颜色设置,重写它们等的练习。对我来说似乎有点低效。

I am a newbie to objective-c and I have an architectural or design pattern question. I am building an ios app and like most ios apps, it uses various colors, font, patterns etc. Perhaps I am currently writing code incorrectly but I find myself rewriting things like color settings. And as a result, changing colors becomes an exercise in finding all of the color settings in the code, rewriting them, etc. Seems a bit inefficient to me.

例如,我在我的应用中的多个位置使用深红色。我倾向于频繁地编写[UIColor colorWithRed ...]方法。但是,我很好奇是否创建一个返回我的自定义颜色的单例(作为UIColor)是模块化我的样式包的合理方法。因此,我可以写这样的东西

For example, I use a dark red color in multiple places in my app. I tend to write the [UIColor colorWithRed...] method rather frequently. However, I curious if creating a singleton that returns my custom colors (as a UIColor) is a reasonable approach to "modularizing my style package." Thus I could write something like this

[label setTextColor:[[MyStyleSingletonClass sharedStyler] myDarkRed]];

因此,如果设计师突然希望myDarkRed变得更暗,我会改变它一次,它是很高兴看到应用程序。显然,风格和用户体验比色彩还要多,但我很好奇这种方法是否有意义,或者我是否为将来的问题做好准备。或者也许这个功能已经存在于objective-c中,我忽略了这一点。提前致谢。

Thus, if the designers suddenly want myDarkRed to be a touch darker, I change it once and it is good to go across the app. Clearly there is more to style and UX than color, but I am curious if this approach makes sense or if I am setting myself up for issues in the future. Or maybe this capability exists in objective-c already and I am missing the point. Thanks in advance.

推荐答案

我认为对这样的事情更好的方法是UIColor本身的一类类方法。我经常为具有大量自定义颜色的项目编写颜色类别。

I think a better approach to something like this is a category of class methods on UIColor itself. I often write categories of colors for projects with lots of custom colors.

这样的事情:

// UIColor+AppAdditions.h
@interface UIColor (AppAdditions)

+ (UIColor *)myDarkRed;

@end

// UIColor+AppAdditions.m

#import "UIColor+AppAdditions.h"

@implementation UIColor (AppAdditions)

+ (UIColor *)myDarkRed
{
    return [UIColor colorWithRed:0.1 green:0.0 blue:0.0 alpha:1.0];
}

@end

这样你就不会需要一个完整的Singleton,而且它更便携,而Singleton做其他事情。你可以干净利地访问你的颜色:

That way you don't need a whole Singleton and its more portable incase the Singleton does other things. And you can cleanly access your colors like this:

[label setTextColor:[UIColor myDarkRed]];

注意

正如Rob和Paul所说。最好恰当地命名它们。我取了你的名字,但最好将它们专门命名为使用它们,并遵循前缀和后缀等惯例。

As mentioned by Rob and Paul. It is best to name them appropriately. I took the name you had but it would be best to name them specifically for their use and follow conventions such as prefixing and suffixing.

这篇关于使用单例来创建基本样式助手类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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