[英]How to add properties/methods to UIButton
我需要向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]);
我应该在日志中得到两个“最终”字符串和两个描述。 但是,我只得到两个描述字符串:
[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,因此这是可以预期的。 也许我应该默认实现自定义控件...
据我所知,该文档没有说不推荐UIButton
子类化。
我已经多次添加自定义属性,而没有出现问题。 唯一要做的就是使用以下命令创建按钮:
[Button buttonWithType:UIButtonTypeCustom]; // won't work for other button types though
使用类别 。
@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;
}
@结束
然后打电话
MyButton *btn = [MyButton buttonWithType:UIButtonTypeRoundedRect];
应该给你你想要的。 buttonWithType
应该在您的子类上调用initWithFrame
。
我发现使用SDK的当前实现无法完成该任务。
类别可能会有所帮助。 像这样实现:
//In the UIButtonMyExtras.h file
@interface UIButton(MyExtras)
//extras
@end
//In the UIButtonMyExtras.m file
@implementation UIButton(MyExtras)
//extra implementation
@end
这会将这些额外功能添加到项目中的每个UIButton。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.