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

时间:2016-05-24 17:56:06

标签: ios swift uibutton uistoryboardsegue sender

我试图通过" show"将UIColor传递给另一个viewController。 segue,以便背景的颜色可以与所选颜色按钮的颜色相匹配。我有一些代码打印按钮发送者标签,但它没有执行该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的标识符与故事板中的标识符匹配。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:4)

要检查的一些事项:

  • 左视图控制器是否在IB中为您分配了类?
  • 是否真的触发了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.
}