2011-09-17 46 views
6

目前,我試圖通過下面的代碼編程觸發「didSelectViewController」的方法:如何以編程方式觸發方法「tabBarController:didSelectViewController:」?

self.tabController.selectedViewController 
     = [self.tabController.viewControllers objectAtIndex:NEWSTAB_INDEX]; 

然而,「didSelectViewController」法不叫。如何觸發該方法而無需手動選擇標籤欄?

+1

注:的TabBar的委託方法「tabBarController:didSelectViewController:」的行爲在iOS 3中發生了變化。在3之前的版本中,調用了此方法,用於對所選視圖控制器進行編程和用戶啓動的更改。在iOS 3及以上版本中,僅在用戶點擊標籤欄時調用它,並且在代碼以編程方式更改標籤欄內容時不會調用它。 – albertamg

+0

我想知道你爲什麼想要達到這個目標。 – Raptor

回答

16
self.tabController.selectedIndex = NEWSTAB_INDEX; // to actually switch to the controller (your code would work as well) - not sure if this does or not send the didSelectViewController: message to the delegate 
[self.tabController.delegate tabBarController:self.tabController didSelectViewController:[self.tabController.viewControllers objectAtIndex:NEWSTAB_INDEX]]; // send didSelectViewController to the tabBarController delegate 
+0

這工作。我測試過了! – user523234

+0

是的,它也適用於我。但爲什麼你必須這樣做?在我的情況下,UITabbarControllerDelegate是一個單獨的類NSObject,並實現委託方法。問題是,如果我切換標籤programaticaly,委託方法不會被調用。如果您通過點擊標籤本身進行切換,它將起作用。還不知道爲什麼會發生。 – Zsolt

+0

@Zsolt這就是蘋果公司認爲委託人(用戶交互觸發)的方式,而且它在某種意義上是有道理的。當以編程方式更改時,您已經知道它已更改,因此在某些情況下觸發委託可能沒有意義。 –

0

對於SWIFT 3.0 您可以通過編程調用這樣

self.tabController.selectedIndex = index (e.g. 0,1...etc) 
self.tabController.delegate.tabBarController(self.tabController, didSelectViewController: self.tabController.viewControllers[index]) 
相關問題