我确信我有两个视图控制器,它们有适当的文件作为它们的类。 (ViewController1.swift和ViewController2.swift)我试图使用以下代码将数据从一个视图控制器传递到另一个视图控制器;但我收到错误" UIView Controller无法转换为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!
}
}
}
答案 0 :(得分:1)
以下示例适用于我。第一个视图控制器的代码:
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!
}
}
}
在第二个视图控制器中:
class ViewController2: UIViewController {
var passedText: String = ""
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "passed: \(self.passedText)"
}
}
别忘了在故事板中命名segue:
您的目标视图控制器指的是错误的控制器。您应该在代码中使用此代码,而不是as! ViewController1
:
let vc = segue.destinationViewController as! ViewController2
还需要修正IBOutlet
名称,vc.toPass = self.textField.text!
应该是:
vc.toPass = self.labeld.text!
确保为第二个视图控制器设置了自定义类:
答案 1 :(得分:0)
可能只是ViewController2未被声明为UIViewController的子类 在ViewController2文件的顶部,您将声明如下:
class ViewController2: UIViewController {
\\ ...
}
答案 2 :(得分:0)