swift - 检测 UITabBar 项目何时选择 swift

标签 swift xcode7

我已经通过界面生成器向我的应用程序添加了一个 UITabBar,并成功地将选项卡链接到其他 View Controller 中的选项卡栏项目,运行应用程序可以在它们之间正常切换。我将如何去检测一个选项卡是否被按下?选择时,我想在选定的选项卡 View Controller 类中调用一个函数。正如您可能会说的那样,我对 swift 还很陌生,所以非常感谢您的解释。

我找不到最近的答案,所有答案似乎都是针对非 swift 或非常旧版本的 xcode。

最佳答案

您不希望 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 - 检测 UITabBar 项目何时选择 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467140/

相关文章:

swift - 使用 setCollectionViewLayout 导致崩溃,说找不到 layoutAttributesForItemAtIndexPath

xcode - 如何滚动 Storyboard预览?

ios - @objc 迁移到 Swift 2 时出错

Swift 包管理器导致 Alamofire 产生错误

ios - 字符串不可转换为 [AnyObject]

ios - 在 iOS 中使用 Swift 数据库

ios - 如何在 iOS 上处理带有 .m3u8 文件的 CloudFront 签名 Cookie?

swift - 声明枚举路由器 Alamofire swift 2.0

ios - UITextView 不会将输入工具栏切换到自定义键盘

ios - 为了能够在 View 与 Storyboard 场景之间按住 Ctrl 键并拖动一个 segue,先决条件是什么