使用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?
推荐答案
使用segues将AnyController中的值设置为第二个
像这样:
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。设置第二个代表查看
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屋!