5

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

    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];

这是我想在触摸 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];
}

谢谢你的帮助。

4

3 回答 3

5

Crash 的原因:你的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];
}

正如 Jacob Relkin 在这里的回答中所说:

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

于 2011-05-17T14:56:12.387 回答
5

好的,你有两个问题。一个是如上所述的选择器问题,但您真正的问题是:

[alertButton addTarget:self.tableView 
                action:@selector(showAlert:) 
      forControlEvents:UIControlEventTouchUpInside];

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

您想将该代码更改为:

[alertButton addTarget:self 
                action:@selector(showAlert) 
      forControlEvents:UIControlEventTouchUpInside];
于 2011-05-17T21:43:05.047 回答
3

Jhaliya 是正确的,但这里有一个简短的解释。

当您配置按钮的目标时,您定义了这样的选择器:

@selector( showAlert: )

冒号 (:) 为需要一个参数的选择器建立方法签名。但是,您的方法被定义为-showAlert,不带任何参数,因此您的对象实际上并没有实现您告诉UIButton调用的方法。如 Jhaliya 所示重新定义您的方法将起作用,将按钮目标的选择器更改为:

@selector( showAlert )
于 2011-05-17T15:01:21.810 回答