通過你的問題的文字是真不明白,你要什麼樣的快捷方式 - 一個單一的顏色,創造的RGBA顏色與值[0..255]
?
DrummerB回答了第一個,Justin Boo第二個。
我想提出一個解決方案,適合兩種:
創建類別,可以涵蓋
[UIColor colorWith255ValuesWithRed: 128 green: 35 blue: 40 alpha:255]
,一個包裝的方法,使用的是現在
- 創建UIColor類的方法,它將UIColor對象存儲在一個靜態的NSMutableDictionary中,它們的名稱和計數器部分,你可以調用如
[UIColor registeredColorWithName:@"activeForegroundColor"]
我寫了一個顏色寄存器想法的示例代碼:
UIColor + Register。ħ
#import <UIKit/UIKit.h>
@interface UIColor (Register)
+(void)registerColor:(UIColor *)color
forName:(NSString *)name;
+(UIColor *)registeredColorForName:(NSString *)name;
+(void)unregisterColorForName:(NSString *)name;
@end
的UIColor + Register.m
#import "UIColor+Register.h"
@interface UIColor (RegisterPrivate)
+(NSMutableDictionary *)colorRegister;
@end
@implementation UIColor (RegisterPrivate)
+(NSMutableDictionary *)colorRegister
{
static dispatch_once_t once;
static NSMutableDictionary *register_;
dispatch_once(&once, ^{
register_ = [NSMutableDictionary dictionary];
});
return register_;
}
@end
@implementation UIColor (Register)
+(void)registerColor:(UIColor *)color
forName:(NSString *)name
{
[[self colorRegister] setObject:color forKey:name];
}
+(UIColor *)registeredColorForName:(NSString *)name
{
return [[self colorRegister] objectForKey:name];
}
+(void)unregisterColorForName:(NSString *)name
{
[[self colorRegister] removeObjectForKey:name];
}
@end
用法:
寄存器
[UIColor registerColor:[UIColor redColor] forName:@"activeColor"];
[UIColor registerColor:[UIColor grayColor] forName:@"passiveColor"];
訪問
[view1 setBackgroundColor:[UIColor registeredColorForName:@"passiveColor"]];
[view2 setBackgroundColor:[UIColor registeredColorForName:@"activeColor"]];
註銷
[UIColor unregisterColorForName:@"activeColor"];
'myColor'將有被分配到一個方法或函數的內部,但這肯定比定義看起來像一個常量但實際上是一個調用要好。 –