Search code examples
iosonclickcrashuibuttonaddtarget

iOS click on dynamic UIButton crashes


I'm creating programmatically a UIButton with an Image.

UIButton * bericht = [[UIButton alloc] initWithFrame:CGRectMake(tableView.bounds.size.width- height, 0, height, height)];
[bericht setBackgroundImage:[UIImage imageNamed:@"bericht.png"] forState:UIControlStateNormal];
[bericht addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:bericht];

- (void) imageClicked:(UIButton *) sender {
   NSLog(@"test message");
}

When I click on this button I got the following error code:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 
'-[__NSSetM goToFirstTrailer:]: unrecognized selector sent to instance 0x7fdaf1e73fe0'

Does anyone know a solution?


Solution

  • Change your selector method to imageClicked.

    UIButton * bericht = [[UIButton alloc] initWithFrame:CGRectMake(tableView.bounds.size.width- height, 0, height, height)];
    
    [bericht setBackgroundImage:[UIImage imageNamed:@"bericht.png"] forState:UIControlStateNormal];
    [bericht addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:bericht];
    
    - (void) imageClicked:(UIButton *) sender {
       NSLog(@"iaksdkjas");
    }