prepareForSegue函数不起作用

时间:2015-12-04 00:41:39

标签: ios swift segue

我确信我有两个视图控制器,它们有适当的文件作为它们的类。 (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!
    }
  }


}

3 个答案:

答案 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:

enter image description here

您的目标视图控制器指的是错误的控制器。您应该在代码中使用此代码,而不是as! ViewController1

let vc = segue.destinationViewController as! ViewController2

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

vc.toPass = self.labeld.text!

确保为第二个视图控制器设置了自定义类:

enter image description here

答案 1 :(得分:0)

可能只是ViewController2未被声明为UIViewController的子类 在ViewController2文件的顶部,您将声明如下:

    class ViewController2: UIViewController {

    \\ ...

}

答案 2 :(得分:0)

您是否在故事板中设置了名称?在自定义类下,Class需要指向视图控制器关联的类。

enter image description here

  

此类不是密钥的符号密码值   labelPassedData“。但我甚至没有变量之类的   labelPassedData

单击您查看控制器并按右箭头按钮,它显示所有连接。

enter image description here

我猜你复制并粘贴了视图控制器,因此你遇到了这个问题。