swift - 检测何时按下标签栏项目

标签 swift uitabbarcontroller uitabbar

我有一个 Root View Controller ,它没有设置为 Storyboard上任何 View Controller 的自定义类。相反,我所有的 View Controller 都像这样子类化这个类。

// RootViewController
class RootViewController: UIViewController, UITabBarDelegate { 

    // This is not getting executed on any of the view controllers
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        print("ddd")
    }
}

// Subclassing it 
class TopStoriesViewController: RootViewController {

}

但是当在子类化 rootviewcontroller 的 View Controller 上按下 tabbaritem 时,我似乎正在努力做某事,即没有打印消息。

最佳答案

您不希望 View Controller 的基类是 UITabBarDelegate。如果你这样做,你所有的 View Controller 子类都将是标签栏委托(delegate)。我认为您想做的是扩展 UITabBarController,如下所示:

class MyTabBarController: UITabBarController, UITabBarControllerDelegate {

然后,在该类中,覆盖 viewDidLoad 并将委托(delegate)属性设置为 self:

self.delegate = self

注意:这是设置标签栏 Controller 委托(delegate)。标签栏有它自己的委托(delegate) (UITabBarDelegate),由标签栏 Controller 管理,您不能更改。

所以,现在这个类既是 UITabBarDelegate(因为 UITabBarController 实现了该协议(protocol)),又是 UITabBarControllerDelegate,您可以根据需要覆盖/实现这些委托(delegate)的方法,例如:

// UITabBarDelegate
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    print("Selected item")
}

// UITabBarControllerDelegate
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    print("Selected view controller")
}

我猜您可能对后者更感兴趣。查看文档以了解每个代表提供的内容。

最后,在您的 Storyboard 中(假设您使用的是 Storyboard ),在 Identity Inspector 中将选项卡栏 Controller 的类设置为 MyTabBarController,这样就可以了。

swift 3/4

// UITabBarDelegate
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print("Selected item")
}

// UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    print("Selected view controller")
}

关于swift - 检测何时按下标签栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837475/

相关文章:

cocoa-touch - 添加一个 TabBarController 作为 View 的 subview

iOS 11 UIBarButtonItem 图像未调整大小

ios - UITabbar 在 iPad 和 iPhone 中的外观变化

ios - UISplitViewController 与 tableView 作为详细 View 错误

ios - 照片浏览器的方向问题

ios - 每次单击 'more' 选项时导航回选项卡选项表

ios - UITabBarViewController 的自定义 TabBar 布局

swift - 将 indexOf() 与 UIButton 类型的数组一起使用

ios - 在 Swift 3 迁移后从编译器警告中找到不兼容的 Objective-C 类别定义

ios - UITextView 未在键盘中显示地球图标