gpt4 book ai didi

ios - 如何在 Swift 中的 View Controller 和其他对象之间共享数据?

转载 作者:行者123 更新时间:2023-11-30 12:11:21 24 4
gpt4 key购买 nike

假设我的 Swift 应用程序中有多个 View Controller ,并且我希望能够在它们之间传递数据。如果我在 View Controller 堆栈中处于较低的几个级别,如何将数据传递到另一个 View Controller ?或者在选项卡栏 View Controller 中的选项卡之间?

(注意,这个问题是一个“铃声”。)这个问题被问得太多了,所以我决定写一个关于这个主题的教程。请参阅下面我的回答。

最佳答案

您的问题非常广泛。认为每种情况都有一个简单的包罗万象的解决方案有点天真。那么,让我们来看看其中的一些场景。

<小时/>

根据我的经验,在 Stack Overflow 上询问的最常见场景是从一个 View Controller 到下一个 View Controller 的简单传递信息。

如果我们使用 Storyboard,我们的第一个 View Controller 可以覆盖 prepareForSegue,这正是它的用途。调用此方法时会传入一个 UIStoryboardSegue 对象,它包含对目标 View Controller 的引用。在这里,我们可以设置我们想要传递的值。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MySegueID" {
if let destination = segue.destination as? SecondController {
destination.myInformation = self.myInformation
}
}
}

或者,如果我们不使用 Storyboard,那么我们将从 Nib 加载 View Controller 。那么我们的代码稍微简单一些。

func showNextController() {
let destination = SecondController(nibName: "SecondController", bundle: nil)
destination.myInformation = self.myInformation
show(destination, sender: self)
}

在这两种情况下,myInformation 是每个 View Controller 上的一个属性,保存需要从一个 View Controller 传递到下一个 View Controller 的任何数据。显然,它们不必在每个 Controller 上具有相同的名称。

<小时/>

我们可能还想在 UITabBarController 中的选项卡之间共享信息。

在这种情况下,它实际上可能更简单。

首先,让我们创建一个 UITabBarController 的子类,并为它提供我们想要在各个选项卡之间共享的任何信息的属性:

class MyCustomTabController: UITabBarController {
var myInformation: [String: AnyObject]?
}

现在,如果我们从 Storyboard构建应用程序,只需将选项卡栏 Controller 的类从默认的 UITabBarController 更改为 MyCustomTabController 即可。如果我们不使用 Storyboard,我们只需实例化此自定义类的实例而不是默认的 UITabBarController 类,并将我们的 View Controller 添加到其中。

现在,标签栏 Controller 中的所有 View Controller 都可以访问此属性,如下所示:

if let tbc = self.tabBarController as? MyCustomTabController {
// do something with tbc.myInformation
}

通过以相同的方式子类化 UINavigationController,我们可以采用相同的方法在整个导航堆栈中共享数据:

if let nc = self.navigationController as? MyCustomNavController {
// do something with nc.myInformation
}
<小时/>

还有其他几种情况。这个答案绝不涵盖所有这些。

关于ios - 如何在 Swift 中的 View Controller 和其他对象之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com