我到处寻找解决方案,但没有。我有两个视图控制器,我想将数据从viewController.swift传递到resultViewController.swift(容器视图),我运行时已成功发送数据。但当我点击增加按钮时,我无法再次发送数据。
ViewController.swift:
class ViewController: UIViewController {
var result: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// performSegueWithIdentifier("sendResult", sender: <#AnyObject?#>)
}
@IBAction func increas(sender: AnyObject) {
result++
performSegueWithIdentifier("sendResult", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "sendResult"{
var resultVC = segue.destinationViewController as! ResultViewController
resultVC.result = self.result
}
}
}
ResultViewController.swift:
class ResultViewController: UIViewController {
var result: Int!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
resultLabel.text = "\(result)"
}
}
答案 0 :(得分:0)
确定。这是一些有效的代码。
首先,删除您的增加方法,然后从Connections Inspector中的按钮中取消它。然后在Interface Builder中删除旧的segue,并通过从按钮拖动到ResultsViewController
来创建一个新的segue。确保在Interface Builder中为segue指定“sendResult”标识符。在ViewController
:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "sendResult" {
result++
var rvc = segue.destinationViewController as! ResultViewController
rvc.result = result
}
}
然后在ResultsViewController
:
@IBOutlet weak var resultLabel: UILabel!
var result : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
resultLabel.text = "\(result)"
// Do any additional setup after loading the view.
}
答案 1 :(得分:0)
嵌套的ViewControllers使用起来有点棘手,因为从父控制器的角度来看,他们看到的只是UIView
(没有rootViewController
或nestedViewController
属性,这将是很高兴有。)
我发现从嵌套控制器发送/读取数据的最佳方法是在父控制器上添加对它的引用。
事实证明,对于所有嵌套视图控制器,在prepareForSegue
之后调用viewDidLoad
。然后再也不会再调用它,除非你手动调用它。但你不应该也不需要这样做。
以下是如何获取对嵌套控制器的引用,以便稍后在代码中使用:
class ViewController: UIViewController {
var result: Int = 1
private var resultVC: ResultViewController? // Keep it optional
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func increas(sender: AnyObject) {
result++
// Update result value, keep optional reference for security
// Here you could write & read values, call methods, etc.
resultVC?.result = result
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "sendResult" {
// Save reference to child view controller (use optional)
resultVC = segue.destinationViewController as? ResultViewController
}
}
}
一旦您拥有对嵌套视图控制器的引用,就可以在代码中的任何位置使用它。为安全起见,请始终将其与?
一起使用。