Get callback/execute some code when a tab on Tab B

2019-08-05 22:19发布

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?

4条回答
相关推荐>>
2楼-- · 2019-08-05 22:33
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...

查看更多
Explosion°爆炸
3楼-- · 2019-08-05 22:39

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楼-- · 2019-08-05 22:49

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 :)

查看更多
何必那么认真
5楼-- · 2019-08-05 22:52

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

查看更多
登录 后发表回答