Objective-C使用typedef枚举来设置类行为,就像Cocoa一样
题
我扩展了UIButton类,以便能够设置UINavigationBarButton的字体和颜色(来自这个代码示例:打开代码)
我是这样的:
@interface NavBarButtonGrey : UIButton
-(id)init;
@end
@implementation NavBarButtonGrey
-(id)init {
if(self = [super init]) {
self.frame = CGRectMake(0, 0, 49.0, 30.0);
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
UIImage *image = [UIImage imageNamed:@"greyNavButton.png"];
UIImage *stretchImage =
[image stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0];
[self setBackgroundImage:stretchImage forState:UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
[self setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
self.titleShadowOffset = CGSizeMake(0, -1);
self.titleLabel.font = [UIFont boldSystemFontOfSize:13];
}
return self;
}
@end
这没关系,但当然不是很灵活。 如何使用typedef枚举(如Apple所做的)来实现所有不同的功能 颜色,字体和大小我希望我的自定义按钮符合。
我唯一可以从UIKit获取的接口文件就是这样做:
typedef enum {
RGCustomNavBarButtonStyleBlue,
RGCustomNavBarButtonStyleGrey,
RGCustomNavBarButtonStyleBlack,
RGCustomNavBarButtonStyleGreen,
RGCustomNavBarButtonStyleRed,
} RGCustomNavBarButtonStyle;
如何从中获取并通过构造函数(initWithStyle)从枚举值中获取字体,大小,颜色等的工作实现?
Objective C中有一个重载构造函数吗?多个构造函数?
希望它有意义并感谢您给予的任何帮助:)
解决方案
您可以拥有多个构造函数,例如;
-(MyClass) initWithFont: (UIFont) font;
-(MyClass) initWithFonmt: (UIFont) font andColor: (UIColor) color;
等
然后将[super init]作为每个自定义构造函数中的第一行。
其他提示
为了扩展上面所说的ennuikiller,我被教导(Hillegass的书)选择一个初始化器<!>#8212;通常是选项最多的那个,比如你的initWithFont:andColor:<!>#8212;并且有其他初始化者称之为。该主要初始化程序称为指定的初始化程序。
所以你的代码将有一个完全实现的initWithFont:andColor:调用[super init],然后你还有一个initWithFont:看起来像这样:
-(MyClass) initWithFont: (UIFont) font
{
[self initWithFont:font andColor:RGCustomNavBarButtonStyleBlack];
}
然后你的initWithFont:andColor:将处理所有其他设置并调用[super init]。
不隶属于 StackOverflow