gpt4 book ai didi

ios - prepareForSegue 函数不起作用

转载 作者:行者123 更新时间:2023-11-29 01:25:22 29 4
gpt4 key购买 nike

我确定我有两个 View Controller ,它们有适当的文件作为它们的类。 (ViewController1.swift 和 ViewController2.swift)我试图使用以下代码将数据从一个 View Controller 传递到另一个 View Controller ;但我收到错误“UIView Controller is not conversionble to ViewController2”。我应该怎么办?我试图改变至于!和 var 来让;都不起作用。

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){

if (segue.identifier == "btnSubmitSegue") {
var svc = segue.destinationViewController as ViewController2;
svc.DataPassed = textField.text

}
}

ViewController2 的代码 导入 UIKit

 class ViewController2: UIViewController {

var toPass: String = ""
@IBOutlet weak var labeld: UILabel!



override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

self.labeld.text = "passed: \(self.toPass)"

}




override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

ViewController1 的代码

  import UIKit

class ViewController1: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}



@IBOutlet weak var textField: UITextField!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == "TheSegue" {
let vc = segue.destinationViewController as! ViewController2
vc.toPass = self.textField.text!
}
}


}

最佳答案

以下示例对我来说效果很好。第一个 View Controller 的代码:

class ViewController: UIViewController {

@IBOutlet weak var textField: UITextField!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == "TheSegue" {
let vc = segue.destinationViewController as! ViewController2
vc.passedText = self.textField.text!
}
}
}

在第二个 View Controller 中:

    class ViewController2: UIViewController {
var passedText: String = ""
@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "passed: \(self.passedText)"
}
}

不要忘记在 Storyboard 中命名 segue:

enter image description here

您的目标 View Controller 引用了错误的 Controller 。你应该在你的代码中有这个,而不是 as! ViewController1:

let vc = segue.destinationViewController as! ViewController2

还需要修改你的IBOutlet名称,vc.toPass = self.textField.text!应该是:

vc.toPass = self.labeld.text!

确保为第二个 View Controller 设置自定义类:

enter image description here

关于ios - prepareForSegue 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078988/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com