6

当我单击 UITableView 中的某个列表项时,我想将单击的项的索引传递给下一个详细视图。

到目前为止,这是我的相关代码:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeworkDetails *view =  [[HomeworkDetails alloc] init];


    int lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
    NSLog(@"%u", lastIndex);

    [self performSegueWithIdentifier: @"HomeworkDetailsSegue" sender:self];
    view.currentIndex = lastIndex;

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

至此,我可以成功进入下一个ViewController(HomeworkDetails)但是信息没有通过。我试图通过这样做来实现这一点,view.currentIndex = lastIndex;但这不起作用。我还能怎么做?对不起,如果我错过了什么;我是 iOS 开发的初学者。

有建议:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


    HomeworkDetails *view =  [[HomeworkDetails alloc] init];


    int lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
    NSLog(@"%u", lastIndex);

    [self performSegueWithIdentifier: @"HomeworkDetailsSegue" sender:self];
    view.currentIndex = lastIndex;

    [tableView deselectRowAtIndexPath:indexPath animated:YES];



}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"HomeworkDetailsSegue"]) {

        // note that "sender" will be the tableView cell that was selected
        UITableViewCell *cell = (UITableViewCell*)sender;
       NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; //**error**


        HomeworkDetails *vc = (HomeworkDetails*)[segue destinationViewController];
        vc.currentIndex = indexPath.row;
    }
}

编译器错误

4

2 回答 2

18

您所描述的最好在prepareForSegue:sender:方法中完成,而不是didSelectRowAtIndexPath:. 在故事板中,确保HomeworkDetailsSegue在 tableView 的原型单元格和目标视图控制器之间设置了 segue。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{    
    if ([segue.identifier isEqualToString:@"HomeworkDetailsSegue"]) {

        // note that "sender" will be the tableView cell that was selected
        UITableViewCell *cell = (UITableViewCell*)sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

        HomeworkDetails *vc = (HomeworkDetails*)[segue destinationViewController];
        vc.currentIndex = indexPath.row;
    }
}

另外,作为风格问题,我建议将您的 HomeworkDetails 类重命名为 HomeworkDetailsViewController。这样做更符合 Apple 的约定,并且更清楚地说明了类代表的内容。

于 2012-04-15T22:17:41.577 回答
0

您应该先在新视图中设置索引属性,然后再使用 performSegueWityIdentifier 对其进行定位。更进一步,最佳实践编码约定要求使用标准prepareForSegue方法设置新视图。

于 2012-04-15T22:13:59.740 回答