推送 UIViewController 时不能在类型上使用实例成员
Posted
技术标签:
【中文标题】推送 UIViewController 时不能在类型上使用实例成员【英文标题】:Instance Member Cannot Be Used on Type when pushing UIViewController 【发布时间】:2019-02-06 15:49:19 【问题描述】:我正在以编程方式设置 ViewControllers(没有情节提要)。
我想将数据传递给下一个 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 但我没有故事板。谢谢!
【问题讨论】:
【参考方案1】:第 1 步:设置目标类
在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
激活时,都会调用foo
的didSet
。
【讨论】:
【参考方案2】:当前的示例代码(上图)正在为静态变量(由CarbonCalculatorResultsViewController.Type
拥有)设置一个值。
我相信您想要实现的是以下内容:
// 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?
nextViewController.userInformation = userInformation
// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)
此示例代码正在为 nextViewController
类型的实例变量 userInformation
设置一个值。
【讨论】:
【参考方案3】:您应该在Object
上传递变量,而不是在Class
上传递变量
替换:CarbonCalculatorResultsViewController.userInformation = userInformation
有:
nextViewController.userInformation = userInformation
注意:
CarbonCalculatorResultsViewController
是Class
。
nextViewController
是Object
。
您的完整代码应如下所示:
// 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?
nextViewController.userInformation = userInformation
// Push next View Controller
self.navigationController?.pushViewController(nextViewController, animated: true)
【讨论】:
以上是关于推送 UIViewController 时不能在类型上使用实例成员的主要内容,如果未能解决你的问题,请参考以下文章
推送新的 UIViewController 时 UISearchController 消失
从导航堆栈推送/弹出uiviewcontroller时如何收到警报