tags:

views:

77

answers:

3

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 class which can call custom handler. How can i create this class and how can i do add custom handler? (i would like same idea with buttonClicjed)

+1  A: 

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];
Nick Bedford
A: 

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
Chuck
A: 

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
Lenny