如何在 iOS 表格视图中每行创建多个点击处理程序



我在表格视图中有一个企业列表,其中包含一些可点击的区域。第一个是在单独的 ViewController 上查看业务详细信息的区域,第二个是致电业务的区域,第三个是在地图上定位业务的区域。

我是iOS的新手,所以我不确定最好的方法。

在Android中,这相当容易。我可以在表适配器的 getView() 方法中执行以下操作:

linearLayoutBusiness.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(context, DetailsActivity.class);
            i.putExtra("business", business);
            context.startActivity(i);
        }
    });

到目前为止,我在cellForRowAtIndexPath方法中拥有的是:

    //business details tap handler
    UITapGestureRecognizer *touchOnBusinessDetails = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(detailsTapHandler)];
    [cell.BusinessInfoView addGestureRecognizer:touchOnBusinessDetails];

    //call view tap handler
    UITapGestureRecognizer *touchOnCallView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(callViewTapHandler)];
    [cell.callView addGestureRecognizer:touchOnCallView];
    //location view tap handler
    UITapGestureRecognizer *touchOnLocationView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(locationViewTapHandler)];
    [cell.locationView addGestureRecognizer:touchOnLocationView];

    return cell;
}
- (void)detailsTapHandler{
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    NSInteger row = selectedIndexPath.row;
    BusinessEntity *businessTapped = businesses[row];
    //open details view
    [self performSegueWithIdentifier:@"detailsSegue" sender:self];
    NSLog(@"detailsView");
}
- (void)callViewTapHandler{
    NSLog(@"callView");
}
- (void)locationViewTapHandler{
    NSLog(@"locationView");
}

我遇到的问题是 selectedIndexPath 始终为 nil,并且我无法发送与 detailsTapHandler 方法中的选定行对应的业务对象。

我走在正确的轨道上吗?或者有更好的方法可以做到这一点吗?

您的选择器应如下所示:

- (void)locationViewTapHandler:(UIGestureRecognizer*)sender 
{
    NSLog(@"locationView");
}

因此,当选择器被触发时,它会作为参数传递手势识别器。然后,可以使用sender.view属性访问附加到笔势识别器的视图。

了解视图后,您可以向上爬网视图层次结构以获取包含它的UITableViewCell,然后调用 [tableView indexPathForCell:cell] ,或者只是将模型索引存储在视图的 tag 属性中,并直接按索引访问模型。

最新更新