How to programmatically configure CallBacks for UIButton?

Manually:

[btnRun addTarget:self action:@selector(RunApp:) forControlEvents:UIControlEventTouchUpOutside]; 

Software built: something like the following:

 - (void) setRunButton:(UIButton*)objectName mySelector:(NSString*)funcName myControlEvent:(NSString*) controlEvent { [objectName addTarget:self action:@selector(funcName) forControlEvents:controlEvent]; } 
0
objective-c cocoa-touch
source share
2 answers

I think you will need something like the following:

 - (void)setRunButton:(UIButton *)objectName mySelector:(NSString *)action myControlEvent:(UIControlEvents)controlEvent { [objectName addTarget:self action:NSSelectorFromString(action) forControlEvents:controlEvent]; } 

It's unusual to pass a selector as an NSString , but you can use NSSelectorFromString() to convert the selector string name to a selector.

The control event parameters are not strings, they are an enumeration, so I changed the myControlEvent parameter to be of type UIControlEvents .

It would be easier to pass the selector to the method using @selector(action) . However, @selector processed at compile time, so the parameter is actually not an NSString . In this case, the method will look like this:

 - (void)setRunButton:(UIButton *)objectName mySelector:(SEL)action myControlEvent:(UIControlEvents)controlEvent { [objectName addTarget:self action:action forControlEvents:controlEvent]; } 
+3
source share

Pass the entire selector as a parameter

 - (void) setRunButton:(UIButton*)objectName mySelector:(SEL)action myControlEvent:(NSString*) controlEvent { [objectName addTarget:self action:action forControlEvents:controlEvent]; } 
+1
source share

All Articles