Pergunta

I have used the following code to add buttons to my tableviewcell , when the button is pressed i need to know which row was it. so i have tagged the buttons (playButton viewWithTag:indexPath.row) The problem is that is if I define the target action method (play) to receive the sender it crashes with "unrecognized selector ", any ides how to know on which row the button was pressed or why it is crashing like this Thanks

-(void)configureCell: (UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[playButton setFrame:CGRectMake(150,5,40,40)];
[playButton viewWithTag:indexPath.row] ; //Tagging the button
[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];
[cell addSubview:playButton];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *beatCell = nil;
beatCell = [tableView dequeueReusableCellWithIdentifier:@"beatCell"];
if (beatCell == nil){
    beatCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"beatCell"];
}
 [self configureCell:beatCell atIndexPath:indexPath];
return beatCell;

}

-(void) play:(id) sender{
UIButton *play = sender;
NSLog(@"Play %i" , play.tag);

}

Foi útil?

Solução

Instead of

[playButton viewWithTag:indexPath.row] ; 

Where you try to receive a subView of UIButton (i dont know why), you should set tag using setter method :

[playButton setTag:indexPath.row];

You also must cast your sender to UIButton type

-(void) play:(id) sender{
UIButton *play = (UIButton *)sender;
NSLog(@"Play %i" , play.tag);
}

Outras dicas

Change one character of this line:

[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];

to

[playButton addTarget:self action:@selector(play:) forControlEvents: UIControlEventTouchUpInside];

When you include parameters on a selector, the colon actually does matter for the Objective C runtime to be able to look up that selector on the object you're targeting.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top