Get callback/execute some code when a tab on Tab Bar is clicked

烈酒焚心 提交于 2019-12-11 10:57:51

问题


Alternatively, I could use something like viewWillAppear, only switching tabs doesn't call viewWillAppear - IF I can access selectedItem or selectedIndex reliably from there.

The goal is to re-use a similar table view, with 3 tabs filling the table with differently filtered data.

I tried overriding didSelect and using the app delegate as UITabBarDelegate, but got the error 'Changing the delegate of a tab bar managed by a tab bar controller is not allowed.'

The tab bar controller, rootCt, is in the app delegate and works correctly.

So that's the trick I'm looking for - getting a notification from the root (tab bar) controller when the index has changed. Ideas?


回答1:


Try implementing an UITabBarController delegate. It has a method similar to the didSelect: method offered by UITabBar delegate:
tabBarController:didSelectViewController:. It will be called after the user has selected another tab.

See: UITabBarControllerDelegate Protocol Reference




回答2:


tabBarController.tabBar.selectedItem.tag

It will give you the tag of current selected tabbar index

If you are using tabBar den

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

is the delegate method that gets called when tabbar is selected.

happy iCoding...




回答3:


You can use the delegate method of UITabBarControllerDelegate

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 

and in that you have self.selectedIndex will give you the selected index.




回答4:


I don't usually do this kind of thing (answer my own question). But here goes.

For example, if I click tab 2, then tab 3, then tab 2 again, viewWillAppear for that view is called, but the didSelectViewController method is not - and selectedIndex is not changed!

It appears as if selectedIndex is only updated if a view is loaded, not if the view is already loaded and simply appears.

I did some testing, and unlike selectedIndex, the tab bar's selectedItem is correctly updated (in viewWillAppear for the view in the clicked tab) even if the view is already loaded. By putting f.ex. the tabs' titles in an array, the matching index can be looked up.

So I will omit the didSelectViewController and won't need a UITabBarController, I only need to connect the UITabBar to an IBOutlet and use [myTabBar selectedItem].title to initialize correctly in the re-used view's viewWillAppear.

If someone offers a more generic/useful/simple solution I'll gladly mark that! Will check back in a few days and mark this if not. Just glad I made it work :)



来源:https://stackoverflow.com/questions/3667818/get-callback-execute-some-code-when-a-tab-on-tab-bar-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!