Reputation:
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
Upvotes: 0
Views: 1418
Reputation: 237110
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
Upvotes: 1
Reputation: 4445
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];
Upvotes: 1