2012-02-28 49 views
0

我需要從我的父視圖控制器到其子視圖獲取NSString。從父ViewController獲取字符串?

所以我有 'ParentView' ----> 'ChildView'

,我需要得到字符串從ParentView到ChildView。我曾嘗試添加一個方法,該方法在我的ParentView中返回一個字符串,並在ChildView中調用它,但沒有運氣。

不起作用:

ViewController *vc = [[ViewController alloc] init]; 
startDateLbl.text = [vc string]; 

任何幫助就如何實現這一目標,將不勝感激,謝謝。

回答

0

這條線ViewController *vc = [[ViewController alloc] init];將創建一個新的對象。

只是給你一個簡單的代碼,希望你得到它

ChildViewController *viewController = [[ChildViewController alloc] initWithNibName:@"ChildViewController" bundle:nil]; 
[self.navigationController pushViewController:viewController animated:YES]; 
//here set your label, make sure startDateLbl has getter property 
viewController.startDateLbl.text = [vc string]; 
+0

工作!謝謝! – 2012-02-28 16:25:05

2

最簡單的方法是設置屬性爲您在子視圖字符串。

@property (nonatomic, retain) NSString *childString; 

然後在將視圖推入堆棧之前或之後,將字符串從父視圖傳遞到子視圖。

ViewController *vc = [[ViewController alloc] initWithNibName:@"ViewController"]; 
vc.childString = parentString; 
[self.navigationController pushViewController:vc animated:YES]; // this assumes navController 
+0

感謝您的回答,儘管設置字符串值僅在您推送視圖後設置時纔有效。 – 2012-02-28 16:25:53

+0

是的喬希這是正確的....你推後的視圖是從xib加載。 – 2012-02-28 16:34:50

+0

不,您可以在分配/初始化視圖後的任意點分配值。您可以在推送視圖之前或之後分配它們。我一直這樣做。 – 2012-02-28 19:09:52

0

根據UIViewController類型,您可能有權訪問父視圖控制器。

self.parentViewController.someString(請參閱UIViewController文檔)。