无法使用 segues 在视图控制器之间传递数据 (Xcode 7) (Swift)

Can't pass data between view controllers using segues (Xcode 7) (Swift)

我一直在努力使用 segues 在视图控制器之间传递数据。我看过许多 youtube 视频教程并在论坛上四处搜索,但我不明白为什么它不起作用。我没有收到任何错误消息,但是当我单击 'Button' 时,模拟器崩溃了。我会喜欢一些帮助!谢谢!

代码如下:

ViewController1 :

    import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    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.
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let destViewController : ViewController2 = segue.destinationViewController as! ViewController2

        destViewController.labelText = textField.text!

    }

}

ViewController2 :

import Foundation
import UIKit

class ViewController2 : UIViewController {

    @IBOutlet var Label: UILabel!

    var labelText : String = ""

    override func viewDidLoad() {

        Label.text = labelText

    }

}

故事板图片:

storyboard image

确保在点击按钮之前在标签 textField 中输入一些文本,因为您正在使用强制展开将该标签的文本传递到下一个场景。

  destViewController.labelText = textField.text! //here compiler expects that your textField has the value

我使用您的相同代码制作了一个示例项目,但没有出现错误。您的代码没有任何问题。

试试这个:转到您的故事板并检查每个视图控制器的插座检查器,并确保您没有无处可去的插座。

如评论中所述,问题是您在 UIViewController 上使用了推送转场。

请注意推送和模态转场已弃用...请查看此 post 条目,如果您有任何疑问请告诉我

What's the difference between all the Selection Segues?