以编程方式调用按钮的操作会导致NSInvalidArgumentException

问题描述 投票:0回答:2

我有一个tableview,每个单元格包含一个文本和一个按钮。对于cellForRowAtIndexPath中每个单元格中的每个按钮,我使用如下选择器定义一个动作:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductCell" forIndexPath:indexPath];

    cell.stateButton.tag = indexPath.row;

    [cell.stateButton addTarget:self action:@selector(stateChange:) forControlEvents:UIControlEventTouchUpInside];

    /// Rest of code

    return cell;
}

在流程中的某个时刻,我想为我的tableview中的所有按钮生成一个动作。我是这样的:

#pragma mark - Delegate
- (void)onAllSwitchesStateChange{

    for(int i = 0; i < [[SsrDeviceManager instance] ssrDevices].count; i ++){

        ProductTableViewCell* cell = (ProductTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        UIButton* stateButton = [cell stateButton];
        [stateButton performSelector:@selector(stateChange:) withObject:nil];

    }
}

这是我的选择器方法:

-(void)stateChange:(UIButton*)sender{

    [self.activityIndicator sizeToFit];
    [sender addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    //// Rest of code
}

但是,为什么我尝试运行此代码,却出现错误,应用程序崩溃并显示以下消息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton stateChange:]: unrecognized selector sent to instance 0x1023686d0'
*** First throw call stack:
(0x233133180 0x23230b9f8 0x23304f9bc 0x25f94c220 0x2331389c8 0x23313a65c 0x101073bdc 0x100fdd844 0x25f922300 0x25f3cb424 0x25f3cb744 0x25f3ca7b0 0x25f9595c4 0x25f95a7ec 0x25f93a85c 0x25fa009d4 0x25fa03100 0x25f9fc330 0x2330c4f1c 0x2330c4e9c 0x2330c4784 0x2330bf6c0 0x2330befb4 0x2352c079c 0x25f920c38 0x10102b794 0x232b828e0)

如何一次为所有按钮生成点击动作

objective-c uitableview uibutton selector performselector
2个回答
0
投票

“如何一次为所有按钮生成点击动作”

这个概念毫无意义。表格视图就是视图。它使用户可以与您(应用程序)进行通信,因为它是可触摸的界面,但它本身并不是活动的来源;它仅代表数据。

如果您希望发生某些事情,将所有按钮转到所有按钮并要求所有按钮启动某种动作是很疯狂的。只需对您自己的数据进行处理,无论您想要做什么。


0
投票

UIButton没有方法stateChange:。您的班级有一个方法stateChange:。您可以只调用自己的类的方法,例如[self stateChange:stateButton]。如果您希望按钮发送消息,如果发生某种特定类型的事件,它将发送该消息,则可以执行[stateButton sendActionsForControlEvents:UIControlEventTouchUpInside]之类的操作。

© www.soinside.com 2019 - 2024. All rights reserved.