gpt4 book ai didi

ios - 推送 UIViewController 时实例成员不能用于类型

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:03 25 4
gpt4 key购买 nike

我正在以编程方式设置 ViewController(无 Storyboard)。

我想将数据传递给下一个 VC,虽然我知道如何使用 segue 和 Storyboard来做到这一点,但我无法弄清楚如何纯粹以编程方式做到这一点。

我收到错误“实例成员不能用于类型...”

// Create Next View Controller Variable

let nextViewController = CarbonCalculatorResultsViewController()

// Pass data to next view controller. There is already a variable in that file: var userInformation: UserInformation?

CarbonCalculatorResultsViewController.userInformation = userInformation

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

在传递数据之前是否需要实例化下一个VC?这就是this answer seems to talk about但我没有 Storyboard。谢谢!

最佳答案

第 1 步:设置目标类(class)

CarbonCalculatorResultsViewController 类中,声明一个 var 来接收数据,如下所示:

class CarbonCalculatorResultsViewController: UIViewController {
var foo: String? {
didSet {
// What you'd like to do with the data received
print(foo ?? "")
}
}

ovevride func viewDidLoad() {
//
}
}

第 2 步:在源类中准备数据

let nextViewController = CarbonCalculatorResultsViewController()
// You have access of the variable in CarbonCalculatorResultsViewController
nextViewController.foo = <data_you_want_to_pass>

// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)

然后,每次 CarbonCalculatorResultsViewController 激活时,foodidSet{} 都会被调用。

关于ios - 推送 UIViewController 时实例成员不能用于类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54557514/

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