如何在prepareForSegue中获取indexpath

时间:2014-10-09 12:42:42

标签: ios uitableview

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
    {
    if ([segue.identifier isEqualToString:@"Action"])
    {
        NSIndexPath *indexPath = [self.tbl indexPathForSelectedRow];
        SecondViewController *destViewController = segue.destinationViewController;
        destViewController.getString = [getArray objectAtIndex:indexPath.row];
    }
}

我想访问所选行index,但为每个选定行显示null。请帮帮我?

4 个答案:

答案 0 :(得分:67)

两种情况:

1)SegueviewController

连接

segue方法拨打didSelectRowAtIndexPath,将indexPath作为sender

传递
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"Action" sender:indexPath];
}

然后,您可以在prepareForSegue:sender:方法

中将indexPath作为发件人
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
 {
     if ([segue.identifier isEqualToString:@"Action"])
      {
           NSIndexPath *indexPath = (NSIndexPath *)sender;
           SecondViewController *destViewController = segue.destinationViewController;
           destViewController.getString = [getArray objectAtIndex:indexPath.row];
      }
  }

2)从细胞连接的segue

无需实施didSelectRowAtIndexPath方法和performSegueWithIdentifier:。您可以在sender方法中直接获取UITableviewCell prepareForSegue:sender:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"Action"])
    {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        SecondViewController *destViewController = segue.destinationViewController;
        destViewController.getString = [getArray objectAtIndex:indexPath.row];
    }
}

答案 1 :(得分:50)

Swift 3.0 / iOS 10

在iOS 9中引入了

tableView.indexPathForSelectedRow

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow{
        let selectedRow = indexPath.row
        let detailVC = segue.destination as! ParkDetailTableVC
        detailVC.park = self.parksArray[selectedRow]
    }
}

答案 2 :(得分:4)

喜欢这个

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender {
    FTGDetailVC *detailVC = (id)segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

    FTGNote *note = self.notes[indexPath.row];
    [detailVC updateWithNote:note];
}

答案 3 :(得分:0)

抱歉,我不明白你想做什么。 当您点击tableView的单元格时,可以通过indexPath.row的{​​{1}}方法获取UITAbleViewDelegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

     self.myVariable = indexPath.row
}

然后您可以通过以下方式访问prepareForSegue中的此值:

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
         //do something with self.myVariable
}

我希望我帮助过你。