Reputation: 439
I have one button in each cell of a UITableView. Now i want to bind each button to its action method in function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...}
Here is my trying code:
NSString* functionNamePrefix = @"actionMethod_";
NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]];
SEL selectorFromString = NSSelectorFromString(functionName);
[button addTarget:self action:@selector(selectorFromString:) forControlEvents:UIControlEventTouchDown];
The failure is : action selector take "selectorFromString" as a function name, but the SEL i convert from string.
Any suggestion? TIA!
Upvotes: 0
Views: 485
Reputation: 4257
Try in this way.
in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...}
[button setTag:indexPath.row];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchDown];
in buttonTapped
-(void)buttonTapped:(UIButton *)button{
switch(button.tag){
//Your code here
}
}
Upvotes: 0
Reputation: 119292
A better way is to assign all of your buttons the same action, and in the action method work out which row the button was in when it was pressed. Otherwise, if your cells get reused, each button will have multiple actions assigned to it which will be very confusing.
You can easily determine the row that a button or other control was in using my answer to this question.
Upvotes: 2
Reputation: 24031
try this way, because you've made already your selector ready to use:
[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown];
Upvotes: 0
Reputation: 3506
If you want the to use the SEL selectorFromString
as selector for your Button, you should change @selector(selectorFromString:)
to selectorFromString
Upvotes: 0
Reputation: 9481
you should pass the selectorFromString to the action parameter and not the @selector(selectorFromString:)
NSString* functionNamePrefix = @"actionMethod_";
NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]];
SEL selectorFromString = NSSelectorFromString(functionName);
[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown];
Upvotes: 1