如何向UIButton添加属性/方法

时间:2011-02-23 19:36:57

标签: iphone objective-c ios4

我需要向UIButton添加两个额外的属性(NSString *和NSMutableArray *)以及三个额外的方法。如果可能的话,我还想使用超类型引用新对象。我不一定想要子类化(因为我读到它很棘手而且不推荐),但我对Objective-C和iOS开发很新,不知道还能做什么。

我尝试将UIButton子类化为我的子类,以下列方式实现正式协议:

@interface Button : UIButton <MyProtocol> ...

然而,我发现这不像我想的那样,因为buttonWithType:从子类返回一个对象。我还能做些什么来达到预期的效果?

- 编辑: 好的,我目前的代码是这样的:

@interface Button : UIButton <SteapeObject> {
    ActionQueue * actions;
    Meta meta;
}

@property (nonatomic, retain) ActionQueue * actions;
@property (nonatomic) Meta meta;

- (id) initWithFrame:(CGRect)frame;
...

实施:

- (id) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        NSLog (@"finally");
    }

    return self;
}

仍然无效。看来,当我调用时:

Button * button = [Button buttonWithType: UIButtonTypeRoundedRect];
NSLog (@"%@", [button description]);

我应该在日志中获得两个'finally'字符串和两个描述。但是,我只得到两个描述字符串:

[Session started at 2011-02-24 09:47:14 +0100.]
2011-02-24 09:47:15.431 IphoneClient3[702:207] <UIRoundedRectButton: 0x5f47690; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x5f47240>>
2011-02-24 09:47:15.461 IphoneClient3[702:207] <UIRoundedRectButton: 0x6a0f000; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x6a344b0>>

你可以看到该类型仍然是UIRoundedRectButton,但按钮不响应我添加的方法。实际上,由于我的覆盖initWithFrame没有被调用,这是可以预料的。也许我应该默认实现自定义控件...

4 个答案:

答案 0 :(得分:2)

据我所知,该文档并未建议不推荐UIButton的子类化。

我已多次添加自定义属性 - 没有问题。 唯一要做的就是使用:

创建按钮
[Button buttonWithType:UIButtonTypeCustom]; // won't work for other button types though

答案 1 :(得分:2)

使用Category

@interface UIButton (MyButtonCategory)
- (void) myMethod;

@end


@implementation UIButton (MyButtonCategory)
- (void) myMethod
{
   NSLog(@"Called myMethod!");
}

@end

[编辑]

或者,如果我最终了解你,你可以这样做。

@interface MyButton : UIButton

- (id) initWithFrame:(CGRect)rect;

@end

@implementation MyButton

- (id) initWithFrame:(CGRect)rect
{
    if ((self = [super initWithFrame:rect])){

    // Do your init in here

    }
    return self;

}

@end

然后调用

MyButton *btn = [MyButton buttonWithType:UIButtonTypeRoundedRect];

应该得到你想要的东西。 buttonWithType应在您的子类上调用initWithFrame

答案 2 :(得分:2)

我发现使用SDK的当前实现无法完成该任务。

答案 3 :(得分:1)

类别可能有所帮助。像这样实施:

//In the UIButtonMyExtras.h file
@interface UIButton(MyExtras)
//extras
@end


//In the UIButtonMyExtras.m file
@implementation UIButton(MyExtras)
//extra implementation
@end

这会将这些额外内容添加到项目中的每个UIButton中。