正在使用tableView:willSelectedRowAtIndexPath:正确的方式来传递变量?
问题描述:
你好,我想传递变量与segue。正在使用tableView:willSelectedRowAtIndexPath:正确的方式来传递变量?
我得到变量传递与tableView:willSelectedRowAtIndexPath:这是正确的方式?如果不是,我该如何实现这一目标? (注意:它是这样工作的。)
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedCoffeeShop = [coffeeShops objectAtIndex:indexPath.row];
return indexPath;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"coffeeShopDetailSegue"]) {
CoffeeShopDetailViewController *controller = (CoffeeShopDetailViewController *)segue.destinationViewController;
[segue destinationViewController];
controller.coffeeShop = selectedCoffeeShop;
}
}
答
如果您的segue是由单元格本身构建的,则不需要实现willSelectRowAtIndexPath或didSelectRowAtIndexPath。你只需要prepareForSegue:发件人:因为发件人参数将是该单元格,你可以用它来得到你需要的indexPath,
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender {
if ([segue.identifier isEqualToString:@"coffeeShopDetailSegue"]) {
NSInteger row = [self.tableView indexPathForCell:sender].row;
CoffeeShopDetailViewController *controller = segue.destinationViewController;
controller.coffeeShop = coffeeShops[row];
}
}
答
这样做绝对没问题。
另一种方法是从故事板中删除自动延期触发器,而是实现: tableView:didSelectRowAtIndexPath:
致电performSegueWithIdentifier:sender:
。
它看起来是这样的:
- (NSIndexPath *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedCoffeeShop = [coffeeShops objectAtIndex:indexPath.row];
[self performSegueWithIdentifier:@"coffeeShopDetailSegue" sender:self];
return indexPath;
}
在这种情况下,你仍然需要你的prepareForSegue:sender:
实现。
您也可以使用UINavigationController
完全不使用segues,但是您必须以编程方式实例化CoffeeShopDetailViewController
。
虽然你的方法非常好!
如注释中所述,您可以删除[segue destinationViewController];
,因为这会返回已保存在上面一行中的变量controller
中的目标视图控制器。 :)
肯定的,只是删除了'[Segue公司destinationViewController]' – AMI289 2014-10-27 12:37:03