几周前我问了this问题并得到了非常详细的解释。现在我想将数据传回第一个 ViewController,但我一直使用相同的方法卡住。我有一个从第一个 VC 到第二个的模式,我想在其中编辑一个字符串数组,它将再次显示在第一个 View 中。所以在我的第一个 View 中,我有一个数据数组,应该传递给第二个,因此编辑字段显示当前信息,之后用户必须能够编辑数组的内容并将该数据传递回第一个它显示在标签上。我正在使用 Swift。
我的代码:
(在 ViewController.swift 中:)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let secondVC = segue.destinationViewController as SecondViewController
secondVC.namesPlayers = self.namesPlayers
}
(在 SecondViewController.swift 中:)
override func viewDidLoad() {
super.viewDidLoad()
labelFirstPlayer.text = namenSpelers[0]
}
谢谢
最佳答案
您需要使用委托(delegate)。这是一个如何在 Swift 中使用委托(delegate)的示例。
在您的第一个 ViewController 上,在加载第二个 VC 时设置您的委托(delegate):
例如,如果您使用 Storyboard编辑器:
var secondViewController = (segue.destinationViewController.visibleViewController as MySecondViewControllerClass)
secondViewController.delegate = self
写一个协议(protocol)并定义一个函数来写回你的值
例如,创建一个名为“Protocol.swift”的文件并编写如下内容:
protocol writeValueBackDelegate {
func writeValueBack(value: String)
}
将函数添加到您的 FirstViewController
func writeValueBack(value: String) {
// Or any other function you need to transport data
}
还有你的 ViewControllerClass
class ViewController: UIViewController, writeValueBackDelegate
如果您没有实现您在协议(protocol)文件中定义的 ViewController
中的所有方法,则以上行将不起作用。
转到第二个 View Controller ,并在此处添加委托(delegate):
class SecondViewController: ViewController {
// Delegate for FirstViewController
// Declare as weak to avoid memory cycles
weak var delegate: writeValueBackDelegate?
}
在您的第二个 View Controller 上,您现在可以使用它来调用第一个 View Controller 中的函数并传递数据。
delegate?.writeValueBack("That is a value")
关于ios - 从 View Controller Xcode 传回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25522912/