天天看點

iOS Storyboard 中多個view 之間傳送資料 iOS Storyboard 中多個view 之間傳送資料

iOS Storyboard 中多個view 之間傳送資料

在iOS中,多個View 之間交換資料是最常見的。比如點選聯絡人清單中某個人,然後新視窗顯示這個聯絡人詳情。

如果這兩個view 是由代碼完成生成,通過操作對象指針可以簡單處理。但是如果兩個view是在Storyboard繪制如何處理?而且跳轉關系是自動調用perfomSegua調轉,這時已經無法看對象指針。

一. 使用要點

首先參見兩篇教程

參見 http://www.mybringback.com/tutorial-series/12396/ios-passing-data-between-views/

http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

+在跳轉前的view 重載prepareForSegue

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  • segua中有一個變量destinationViewController即是下一個view的執行個體

    對其指派即可

二.代碼片斷

示例1:

-(void)prepareForSegue:(UIStoryboardSegue )segue sender:(id)sender {

if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {

NSIndexPath indexPath = [self.tableView indexPathForSelectedRow];

RecipeDetailViewController *destViewController = segue.destinationViewController;

destViewController.recipeName = [recipes objectAtIndex:indexPath.row];

}

}

注意這裡有一個強制轉換

RecipeDetailViewController *destViewController =segue.destinationViewController;

示例2:

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

if ([segue.identifier isEqualToString:@"hello"]) {

NSString *intro = @"Hello my friend.";

ViewController2 *vc = [segue destinationViewController];

vc.introString = intro;

} else if ([segue.identifier isEqualToString:@"hola"]) {

NSString *intro = @"Hola mi amigo.";

ViewController2 *vc = [segue destinationViewController];

vc.introString = intro;

} else if ([segue.identifier isEqualToString:@"bam"]) {

UIImage *image = [UIImage imageNamed:@"12.png"];

ViewController2 *vc = [segue destinationViewController];

vc.introImage = image;

}

}

測試程式下載下傳

http://dchabmztumu0g.cloudfront.net/wp-content/uploads/2012/10/prepareForSegueTut2.zip

https://dl.dropboxusercontent.com/u/2857188/RecipeBookSimple.zip