与发件人一起准备 Swift 中的 Segue

Prepare for Segue in Swift with Sender

我正在尝试通过 "show" segue 将 UIColor 传递给另一个 viewController,以便背景颜色可以与所选颜色按钮的颜色相匹配。我有这段代码可以打印按钮发件人标签,但它没有执行那个 segue。

我做错了什么?我以前从未使用过发件人标签,所以这可能很愚蠢,但我不确定。

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

        if segue.identifier == "toQuiz" {
            if sender?.tag == 1 {

                let viewController:ViewController = segue.destinationViewController as! ViewController
                let color = UIColor.blueColor()
                viewController.passedColor = color

            } else if sender!.tag == 2 {

                let viewController:ViewController = segue.destinationViewController as! ViewController
                let color = UIColor.greenColor()
                viewController.passedColor = color

            } else if sender!.tag == 3 {

                let viewController:ViewController = segue.destinationViewController as! ViewController
                let color = UIColor.yellowColor()
                viewController.passedColor = color

            }
        }
    }

    @IBAction func athButtonTapped(sender: AnyObject) {

        let athleteQuiz = sender as! UIButton
        print("Button \(athleteQuiz.tag) was pressed!")
    }

    @IBAction func actorButtonTapped(sender: AnyObject) {

        let actorQuiz = sender as! UIButton
        print("Button \(actorQuiz.tag) was pressed!")
    }

    @IBAction func musicButtonTapped(sender: AnyObject) {

        let musicQuiz = sender as! UIButton
        print("Button \(musicQuiz.tag) was pressed!")
    }

这是故事板布局 - 它们都已正确连接,并且 segue 的标识符与故事板中的标识符相匹配。

一些要检查的东西:

  • 左视图控制器是否在 IB 中分配了您的 class?
  • 是否真的有什么触发了 segue?您的两个按钮操作都不包含对 performSegueWithIdentifier(_:sender:)
  • 的调用

此外,这是一个非常危险的代码块;你不应该像那样强制解包发件人。相反,考虑做这样的事情:

guard let id = segue.identifier else { return } // Bail if there isn't a segue ID.
if id == "toQuiz" {
    guard let tag = (sender as? UIView)?.tag else { return } // Bail if we can't get a tag.

    // Continue examining the tag.
}