0

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!

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Maadiah
  • 431
  • 6
  • 20

5 Answers5

2

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.

Community
  • 1
  • 1
jrturton
  • 118,105
  • 32
  • 252
  • 268
1

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];
CarlJ
  • 9,461
  • 3
  • 33
  • 47
0

If you want the to use the SEL selectorFromString as selector for your Button, you should change @selector(selectorFromString:) to selectorFromString

pre
  • 3,475
  • 2
  • 28
  • 43
0

try this way, because you've made already your selector ready to use:

[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown];
holex
  • 23,961
  • 7
  • 62
  • 76
0

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
     }
}
rakeshNS
  • 4,227
  • 4
  • 28
  • 42