2

我扩展了 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 中是否有一个重载构造函数?多个构造函数?

希望这是有道理的,并感谢您提供的任何帮助:)

4

2 回答 2

2

为了扩展 ennuikiller 上面所说的内容,我被教导(Hillegass 的书)选择一个初始化程序——通常是选项最多的初始化程序,比如你的 initWithFont:andColor:——并让其他初始化程序调用它。该主初始化程序称为指定初始化程序。

所以你的代码会有一个完全实现的 initWithFont:andColor: 调用 [super init],然后你也会有一个 initWithFont: 看起来像这样:

-(MyClass) initWithFont: (UIFont) font
{
    [self initWithFont:font andColor:RGCustomNavBarButtonStyleBlack];
}

然后您的 initWithFont:andColor: 将处理所有其他设置并调用 [super init]。

于 2010-02-03T15:11:52.007 回答
1

您可以有多个构造函数,例如;

-(MyClass) initWithFont: (UIFont) font;
-(MyClass) initWithFonmt: (UIFont) font andColor: (UIColor) color;

等等

然后调用 [super init] 作为每个自定义构造函数的第一行。

于 2009-10-29T11:31:24.603 回答