2014-01-06 34 views
0

我在我的應用程序委託中實現了以下內容,並嘗試檢查選定的索引。但是我發現的是,這個值是當點擊一個新標籤時它所在的標籤,而不是新標籤。有沒有辦法找到哪個標籤被選中?確定在tabbarcontroller中選擇哪個選項卡

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 
{ 
    int *i = tabBarController.selectedIndex; 
} 

回答

0

您想使用tabBarController:didSelectViewController:委託方法。這是在選中標籤後調用的。

而你的int *i實際上應該是int i或更好,NSUInteger i

2

如果我沒有記錯的話,你可以選擇的選項卡的索引與

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 
    NSUInteger selectedIndex = [tabBarController.viewControllers indexOfObject:viewController]; 
    // ... 
    return YES or NO; 
} 
+0

問題是代碼是在錯誤的委託方法,被稱爲前該選項卡實際上已更改。 – rmaddy

+0

@rmaddy:你可能是對的,但是'shouldSelectViewController'通常被實現,如果你想決定選擇新選項卡還是不選。在'didSelectViewController'中,爲時已晚。 –

+0

看來OP想要新的索引。你的代碼檢查新選擇的VC的索引將給出答案。但如果用戶只是想在事後知道新的索引,那麼我的答案似乎更直接。如果需要驗證選擇,那麼當然你的答案會更好。 – rmaddy

0

斯威夫特版本:

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { 
    var shouldSelect = true 
    if let viewControllers = tabBarController.viewControllers where viewControllers.indexOf(viewController) == lastIndex { 
     shouldSelect = false 
    } 
    return shouldSelect 
} 
相關問題