2012-04-22 20 views
0

我有一個TabBarController,它在啓動時設置了多個ViewController。當用戶點擊一個按鈕時,我想將它們發送到TabBarController中的不同ViewController,並通過委託傳遞數據。使用帶有TabBarController的委託

我有一個協議和委託設置。然而,你什麼時候設置委託,因爲所有的ViewControllers在TabBarController

這是可能的,我怎麼能傳遞數據到TabBar中的另一個ViewController當用戶點擊一個按鈕。任何想法,我真的想使用委託。

- (IBAction)sendData:(id)sender 
{ 
    [self.delegate setStringData:strData]; 
    self.tabBarController.selectedIndex = 0; 
} 

編輯:

所以我們可以說我有兩個ViewControllers稱爲ViewControllerOne和ViewControllerTwo一個TabBarController。

我將ViewControllerTwo設置爲委託和協議。這是在按下按鈕後將數據發送到ViewControllerOne的ViewController。 ViewControllerOne實現協議幷包含方法setStringData,該方法在按下ViewControllerTwo中的按鈕後應該調用。

+0

請使用一些科目......哪個類應該是代表?並且應該在哪個類中使用?你將從一個viewController到另一個...然後呢? – meronix 2012-04-22 17:56:42

+0

我會進行編輯以使其更清晰一些。 – Vikings 2012-04-22 18:08:52

回答

0

我找到了一個更簡單的解決我的問題。在ViewControllerTwo內部,我只是創建一個ViewControllerOne的實例,並將它傳遞給我需要的數據。然後我將tabBarController索引更改爲ViewControllerOne。

例如:

// A method inside of ViewControllerTwo 
ViewController *viewcontrollerOne = [ViewcontrollerOne alloc] init]; 
[viewcontrollerOne setStringData:str]; 
[viewcontrollerOne release]; 
self.tabBarController.selectedIndex = 0; 
0

從UIViewController你想要改變選定的標籤欄索引並傳遞數據。 我建議你在這個應用程序代理中添加一個函數。 這樣你的UIViewController將不會與UITabBar綁定(如果明天你想使用不同的UI習慣用法,你只需要在你的應用程序委託中更改你的函數的實現)。爲了傳遞數據,我可以嘗試在你的函數中進行自省:你從新選擇的tab索引中獲取當前的UIViewController,驗證它是否響應你的選擇器並調用函數。

編輯:

讓我們假設你的「只是」必須改變所選的TabBar指數(例如,您的UIViewController將永遠是新的標籤欄指數相同)。

在你的第一個視圖控制器:

 
    - (IBAction)sendData:(id)sender 
    { 
     UIApplicationDelegate * appDelegate = [[UIApplication sharedApplication] delegate]; 
     if ([appDelegate respondToSelector:@selector(goToFirstTabBarWithData:)]) 
     { 
      [appDelegate performSelector:@selector(goToFirstTabBarWithData:) withObject: strData]; 
     } 
    } 

在你的appdelegate:

 
    - (void)goToFirstTabBarWithData:(NSString *)data 
    { 
     self.tabBarController.selectedIndex = 0; 
     UIViewController * vc = [self.tabBarController.viewControllers objectAtIndex:0]; 
     if ([vc respondToSelector:@selector(setStringData:)]) 
     { 
      [vc performSelector:@selector(setStringData:) withObject:data]; 
     } 
    } 

在你的第二個視圖控制器(你將在到達一個):

 
    - (void)setStringData:(NSString *)data 
    { 
     // Do something... 
    } 
+0

我不確定我完全理解這個答案。所以這個方法在AppDelegate中?現在沒有代表和協議?假設我不會改變我的UI習慣用法,你能簡化一下嗎? – Vikings 2012-04-22 18:17:43

+0

和setStringData方法,那將位於哪裏? – Vikings 2012-04-22 18:21:01

+0

您需要將此代碼放入TabBar控制器並在視圖控制器中實現這些方法。 – 2012-04-22 18:54:47