简体   繁体   中英

Event + Handler

How can I create same action like have UIButton or other UI controllers?

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

...

- (void)buttonClicked
{
// Handler
}

I would like to have a class which can call a custom handler. How can I create this class and how can I add a custom handler? (I would like same idea with buttonClicked.)


Chuck, that's exactly what i asked! Thank you! One more things, how can i send one argument to my action. I would like have one NSString parameter in my handler

I would like something like this (but it's not work):

@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

It would be the same as your current handler.

@interface SomeOtherHandler : NSObject
{
}

-(void)onButtonClick:(id)sender;

@end

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

I think you're asking how to implement the target-action callback mechanism. If so, it's really simple:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM