2014-10-27 71 views
0

你好,我想傳遞變量與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; 
    } 
} 
+0

肯定的,只是刪除了'[Segue公司destinationViewController]' – AMI289 2014-10-27 12:37:03

回答

1

如果您的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]; 
    } 
} 
1

這樣做絕對沒問題。

另一種方法是從故事板中刪除自動延期觸發器,而是實現: 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中的目標視圖控制器。 :)