prepareForSegue 传递索引 0 的值...总是

prepareForSegue passes value for Index 0...ALWAYS

我在 TableViewController 中显示了一系列项目。它们在 TVC 中正确显示。下面的代码会继续,但它只会继续到我的 MKMapItem 数组的 indexPath 0,而不是被单击的单元格中的项目。

想知道我的错误在哪里吗?

@property (strong, nonatomic) NSArray *mapItems;

每个单元格都有一个 "Add POI" UIButton,它会触发使用 Interface Builder 创建的名为 "addPOISegue".

的转场

这是 "Add POI" 按钮的 IBAction:

- (IBAction)addPOIButtonClicked:(UIButton *)sender {
    NSLog(@"Add POI button clicked");
    [self performSegueWithIdentifier:@"addPOISegue" sender:sender];
}

这是`prepareForSegue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton*)sender {

//    NSLog(@"The sender is %@", sender);
    if ([[segue identifier] isEqualToString:@"addPOISegue"]) {
        AddPOIViewController *destinationVC = segue.destinationViewController;

        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:sender.center];
        NSLog(@"NSIndexPath *indexPath's index is %@", indexPath);
        MKMapItem *item = _mapItems[indexPath.row];
//        NSLog(@"ResultsTVC item is %@", item);
        destinationVC.item = item;
    }

}

indexPath 一直设置为 0。我怀疑这是因为我有一个按钮触发单元格内的 segue,但我不知道如何解决这个问题。

你应该删除按钮的动作方法,并直接从按钮连接segue到下一个控制器。在 prepareForSegue 中,您可以将按钮的原点,在将其转换为 table 视图的坐标系后传递给 indexPathForRowAtPoint: 方法以获取包含按钮的单元格的 indexPath,

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton*)sender {

    if ([[segue identifier] isEqualToString:@"addPOISegue"]) {
        AddPOIViewController *destinationVC = segue.destinationViewController;
        CGPoint p = [sender convertPoint:CGPointZero toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        NSLog(@"NSIndexPath *indexPath's index is %@", indexPath);
        MKMapItem *item = _mapItems[indexPath.row];
//        NSLog(@"ResultsTVC item is %@", item);
        destinationVC.item = item;
    }

}

@rdelmar 想通了。由于 UIButton 包含在我的单元格中并在我的 prepareForSegue 方法中引用,我需要一个 CGPoint

这段代码让它工作:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton*)sender {

//    NSLog(@"The sender is %@", sender);
    if ([[segue identifier] isEqualToString:@"addPOISegue"]) {
        AddPOIViewController *destinationVC = segue.destinationViewController;

        CGPoint point = [sender convertPoint:CGPointZero toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        NSLog(@"NSIndexPath *indexPath's index is %@", indexPath);
        MKMapItem *item = _mapItems[indexPath.row];
        NSLog(@"ResultsTVC item is %@", item);
        destinationVC.item = item;
    }

}