0

I started with the default Tabbed Application, added some tabs in the Storyboards with their own viewcontrollers, how can I know when a tab that's already selected, get's touched again?

Tab 1 goes to a webview that has loaded other pages, when the user hits the home tab again, when it's still highlighted, I'd like to reload the initial url where it started.

Thanks for any ideas!

4

3 回答 3

0
@interface AHTabBarController () <UITabBarControllerDelegate>
@property (nonatomic, strong) UIViewController* previousViewController;
@end

///

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if ([viewController isEqual:self.previousViewController])
    {
          NSLog(@"reselect tabbar");
    }
    self.previousViewController = viewController;
}
于 2013-12-10T14:15:18.313 回答
0

[– tabBarController:didSelectViewController:]每次触摸标签栏时都会调用UITabBarControllerDelegate 方法。此 API 的文档指出:

在 iOS v3.0 及更高版本中,这个(选择的视图控制器)可能是已经选择的同一个视图控制器。

因此,如果您检测到您的指定选项卡再次被选中,您可以让此委托方法重新加载您的初始 URL。

于 2013-05-17T02:08:17.733 回答
0

这是常见用例的完整答案。


  1. 创建一个protocol用于处理重选

    protocol TabInteractionDelegate {
        func didReselectTab(at index: Int, with item: UITabBarItem)
    }
    
  2. protocol从自定义调用UITabBarController

    class CustomTabBarController: UITabBarController, UITabBarControllerDelegate {
    
        var tabInteractionDelegate: TabInteractionDelegate?
    
        // ...
    
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    
            // This will:
            // 1. Call when the tab is reselected (i.e. The tab does not switch)
            // 2. NOT get called when the tab is switching to a new tab and showing a new view controller
    
            if (tabBar.items?[selectedIndex] == item) {
                 tabInteractionDelegate?.didReselectTab(at: selectedIndex, with: item)
            }
         }
    
    }
    
  3. UIViewController在你需要的地方听改变

    class CustomViewController: UIViewController, TabInteractionDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Attach the delegate 
            if let tabBarCont = tabBarController as? ChoiceTabBarController {
                tabBarCont.tabInteractionDelegate = self
            }
    
        }
    
        // Listen to the change 
        func didReselectTab(at index: Int, with item: UITabBarItem) {
            print("\(index) :: \(item)")
    
            // Here you can grab your scrollview and scroll to top or something else
        }
    
    }
    
于 2021-03-24T19:22:39.670 回答