【问题标题】:UITabViewController with a UINavigationController as a tab带有 UINavigationController 作为选项卡的 UITabViewController
【发布时间】:2016-12-02 15:35:35
【问题描述】:

我的数据由UITabBarController 的两个选项卡共享。第一个选项卡负责生成和更新第二个选项卡所使用的数据数组。

我原来在选项卡之间共享数据的方法奏效了。

                      ------UIViewController
---UITabBarController
                      ------UIViewController

使用上述方法,我从第一个选项卡中访问了数据数组:

let pointsViewController = self.tabBarController?.viewControllers?.first as! ShowPointsViewController
tableHeaders = pointsViewController.tableHeaders 

ShowPointsViewController 是第一个标签

这是我的问题: 当我将我的第一个 UIViewController 嵌入到 UINavigationController 中,然后尝试使用下面的代码访问我的数据数组时,我收到运行时错误,因为 .first... 之后的代码返回为零。我知道我访问不正确,获得相同结果的正确方法是什么?

 let pointsViewController = self.tabBarController?.viewControllers?.first?.navigationController?.topViewController as! ShowPointsViewController

【问题讨论】:

    标签: ios uiviewcontroller swift3 uitabbarcontroller


    【解决方案1】:

    如果我理解得很好,你创造了这样的东西:

                          ------UINavigationController    ------UIViewController
    ---UITabBarController
                          ------UINavigationController    ------UIViewController
    

    self.tabBarController?.viewControllers?.first 已经是 UINavigationController。

    使用以下代码:

     let pointsViewController = (self.tabBarController?.viewControllers?.first as? UINavigationController)?.topViewController as! ShowPointsViewController
    

    【讨论】:

    • Gahhhh 完美这工作。我认为 Swift 的类型推断可以让我避免强制转换为 UINavigationController。出于好奇,为什么这不适用于这里?
    • self.tabBarController?.viewControllers 包含 UIViewControllers 数组。并非所有这些都必须是 UINavigationController (就像在您之前的示例中一样),并且因为您需要获取 UINavigationController 的典型 topViewController 属性,所以您需要强制转换。
    【解决方案2】:

    self.tabBarController?.viewControllers?.first?是你的navigationController,所以你在导航控制器上调用.navigationController,它返回nil

    要解决此问题,请从您的通话中删除 .navigationController

    let pointsViewController = self.tabBarController?.viewControllers?.first?.topViewController as! ShowPointsViewController
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多