事件+处理程序

时间:2009-10-07 23:04:16

标签: objective-c

如何创建与UIButton或其他UI控制器相同的操作?

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];

...

- (void)buttonClicked
{
// Handler
}

我想有一个可以调用自定义处理程序的类。如何创建此类,如何添加自定义处理程序? (我想用buttonClicked来表达同样的想法。)


查克,这正是我的要求!谢谢!还有一件事,我如何向我的行动发送一个论点。我想在我的处理程序中有一个NSString参数

我想要这样的东西(但这不起作用):

@interface Example : NSObject {
    id target;
    SEL action;
}

- (id)initWithTarget:(id)targetObject action:(SEL)runAction;
- (void)activate;
@end

@implementation Example
- (id)initWithTarget:(id)targetObject action:(SEL)runAction {
    if (self = [super init]) {
        target = targetObject;
        action = runAction;
    }
    return self;
}

- (void)activate {
    [target performSelector:action withObject:self withObject: @"My Message"];
}
@end

@interface ExampleHandler : NSObject {

}

-(void):init;
-(void)myHandler:(NSString *)str;

@end

@implementation ExampleHandler

-(void)init {
    [super init];
    Example *ex = [[Example alloc] initWithTarget: self action: @selector(myHandler) ];

}

-(void)myHandler:(NSString *)str {
    NSLog(str);
}

@end

2 个答案:

答案 0 :(得分:1)

它与您当前的处理程序相同。

@interface SomeOtherHandler : NSObject
{
}

-(void)onButtonClick:(id)sender;

@end

// when creating your button
[button addTarget:someOtherHandler action:@selector(onButtonClick:) forControlEvents:UIControlEventTouchUpInside];

答案 1 :(得分:1)

我认为你在问如何实现目标 - 动作回调机制。如果是这样,那很简单:

@interface Example : NSObject {
    id target;
    SEL action;
}

- (id)initWithTarget:(id)targetObject action:(SEL)runAction;
- (void)activate;
@end

@implementation Example
- (id)initWithTarget:(id)targetObject action:(SEL)runAction {
    if (self = [super init]) {
        target = targetObject;
        action = runAction;
    }
    return self;
}

- (void)activate {
    [target performSelector:action withObject:self];
}
@end