无法识别的选择器从UIButton发送到实例错误消息

han*_*Dev 5 iphone objective-c uibutton ios unrecognized-selector

我有一个以编程方式添加到tableview的UIButton.问题是,当它被触摸时,我遇到发送到实例错误消息的无法识别的选择器.

    UIButton *alertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];     
    [alertButton addTarget:self.tableView action:@selector(showAlert:) 
          forControlEvents:UIControlEventTouchUpInside];
    alertButton.frame = CGRectMake(220.0, 20.0, 160.0, 40.0);

    [self.tableView addSubview:alertButton];
Run Code Online (Sandbox Code Playgroud)

这是触摸InfoDark UIButton时我想要触发的警报方法:

- (void) showAlert {
        UIAlertView *alert = 
         [[UIAlertView alloc] initWithTitle:@"My App" 
                                    message: @"Welcome to ******. \n\nSome Message........" 
                                   delegate:nil 
                          cancelButtonTitle:@"Dismiss" 
                          otherButtonTitles:nil];
        [alert show];
        [alert release];
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Jha*_*iya 5

崩溃的原因:你的showAlert功能原型必须是- (void) showAlert:(id) sender.

使用以下代码

- (void) showAlert:(id) sender {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App" message: @"Welcome to ******. \n\nSome Message........" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alert show];
        [alert release];
}
Run Code Online (Sandbox Code Playgroud)

雅各Relkin说,在他的答案在这里:

因为你在addTarget的selector参数中包含了冒号(:),所以接收选择器必须接受一个参数.运行时无法识别选择器@selector(buttonTouched :),因为没有一个方法具有接受参数的名称.更改方法签名以接受id类型的参数以解决此问题.


Gra*_*yer 5

好的,你有两个问题.一个是上面提到的选择器问题,但你真正的问题是:

[alertButton addTarget:self.tableView 
                action:@selector(showAlert:) 
      forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

这是错误的目标,除非您已将UITableView子类化以响应警报.

您想将该代码更改为:

[alertButton addTarget:self 
                action:@selector(showAlert) 
      forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)