使用 Swift 使用 Segue 发送数据 [英] Sending data with Segue with Swift
问题描述
我有两个视图控制器和两个视图.在我的第一个视图中,我将变量currentUser"设置为 false.我需要能够在第二个视图控制器中将currentUser"设置为 true.
I have two view controllers and two views. In my first view, I set the variable 'currentUser' to false. I need to be able to set 'currentUser' to true in the second view controller.
当尝试从第二个视图中引用currentUser"时,它不会选择它,因为currentUser"是在第一个视图控制器中定义的.
When trying to reference 'currentUser' from the second view it's not picking it up as 'currentUser' is defined in the first view controller.
如何使用 segue 传递变量?
How do I carry across variables with segue?
推荐答案
使用 segue 将 Any ViewController 的值设置为第二个
像这样:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "yourIdentifierInStoryboard") {
let yourNextViewController = (segue.destinationViewController as yourNextViewControllerClass)
yourNextViewController.value = yourValue
在 yourNextViewController 类中.
And in your yourNextViewController class.
class yourNextViewControllerClass {
var value:Int! // or whatever
您也可以以编程方式调用它:
You can call this also programmatically:
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
将 DestinationViewController 中的值设置回主(第一个)ViewController
1. 实现一个协议,例如创建一个名为 protocol.swift 的文件.
1. Implement a protocol, for example create a file called protocol.swift.
protocol changeUserValueDelegate {
func changeUser(toValue:Bool)
}
2.在第二个视图上设置代理
2. set the delegate on your second View
class yourNextViewControllerClass {
var delegate:changeUserValueDelegate?
3. 在加载时设置委托 (prepareForSegue)
3. set the delegate on load (prepareForSegue)
if(segue.identifier == "yourIdentifierInStoryboard") {
var yourNextViewController = (segue.destinationViewController as yourNextViewControllerClass)
yourNextViewController.delegate = self
4. 给 FirstViewController 添加函数
4. add Function to FirstViewController
func changeUser(toValue:Bool) {
self.currentUserValue = toValue
}
5. 从你的 SecondViewController 调用这个函数
5. call this function from your SecondViewController
delegate?.changeUser(true)
6. 在 FirstViewController 中设置委托
6. Set the delegate in your FirstViewController
class FirstViewController: UIViewController, ChangeUserValueDelegate {
这篇关于使用 Swift 使用 Segue 发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!