【问题标题】:How to obtain reference to a View Controller from UITabBarViewController如何从 UITabBarViewController 获取对 View Controller 的引用
【发布时间】:2017-12-31 19:14:17
【问题描述】:

编辑:我的方法偏离了基础。我正在尝试将数据从一个 VC 传递到另一个。源 VC 不受 Tab Bar 控制,因此我无法通过它引用目标 VC。我试图通过 Storyboard 引用目标 VC,但目标 VC 上的数据仍然为零。我正在使用 Core Data 并希望将 ManagedObjectContext 传递给另一个 VC。代码如下:

......
                    do {
                        try self.managedObjectContext.save()
                        appUserID = user.userID!
                        } catch {
                        fatalError("Error: \(error)")
                    }
                }
            }
        self.passManagedObjectContext()
    }

    func passManagedObjectContext() {
        let profileTableViewController = UIStoryboard(name: "Profile", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileTableViewController
            profileTableViewController.managedObjectContext = self.managedObjectContext
        }


I am passing data from the AppDelegate to other ViewControllers by referencing my TabBarViewControllers stack like so:



    let tabBarController = window!.rootViewController as! UITabBarController
        if let tabBarViewControllers = tabBarController.viewControllers {
            let profileNavController = tabBarViewControllers[4] as! UINavigationController
            let profileTableViewController = profileNavController.topViewController as! ProfileTableViewController
            profileTableViewController.managedObjectContext = context
        }
    }
.....

结束编辑 我现在正在尝试做同样的事情,但是从一个 ViewController 到另一个通过标签栏访问的 ViewController(没有 segue)。上面的代码不识别window!.rootViewController怎么引用根UITabBarController?

【问题讨论】:

  • 您可以使用 segue 跨标签栏的视图控制器共享数据
  • 您在 AppDelegate 中的何处/何时尝试执行此操作?
  • @DonMag 我之前从 AppDelegate 传递了数据,并试图在 VC 之间使用相同的方法它们不是同一个导航堆栈的一部分,我无法通过标签栏做到这一点,所以我正在尝试通过故事板。谢谢。
  • @MartinMuldoon - 你可能让window!、rootViewController、UITabBarController、传递数据等等变得复杂……而不是考虑你是什么真的很想做。我怀疑你想要做的是access ManagedObjectContext from multiple viewcontrollers?如果是这样,请尝试搜索 that。您可能会发现一种更简单、更灵活的方法。
  • @DonMag.. 是的。在截止日期前赶时间。没有捷径。

标签: ios swift swift3 uiviewcontroller uitabbarcontroller


【解决方案1】:

UIViewController 有一个内置的可选属性tabBarController,所以在你的视图控制器中你可以像这样访问tabBarController

if let tabBarController = tabBarController {
    //get the controller you need from
    //tabBarController.viewControllers
    //and do whatever you need
}

这是Apple's UIViewController documentation 的“获取其他相关视图控制器”部分中可用的当前属性列表:

【讨论】:

  • 我尝试了您的方法,但直到那时才意识到源 VC 不是 Tab Bars 集合的一部分。我正在尝试通过情节提要来做到这一点。仍然没有运气。已更新问题。谢谢。
  • 与其尝试在视图控制器的基础上传递托管对象上下文,您是否尝试过从任何需要它的视图控制器的 AppDelegate 访问它?
猜你喜欢
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 2014-03-26
  • 1970-01-01
相关资源
最近更新 更多