简体   繁体   中英

Prepare for Segue in Swift with Sender

I am trying to pass a UIColor to another viewController via a "show" segue so that the color of the background can match that of the color button that was selected. I have this bit of code that prints the buttons sender tag but it is not performing that segue.

What am I doing wrong? I have never worked with sender tags before so it could be something silly but I am not sure.

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!")
    }

This is the storyboard layout - they are all connected properly and the identifier for the segue matches that in the storyboard.

在此处输入图片说明

在此处输入图片说明

Some things to check:

  • Does the left view controller have your class assigned to it in IB?
  • Is anything actually triggering the segue? Neither of your button actions contain a call to performSegueWithIdentifier(_:sender:)

Also, this is a very dangerous block of code; you should not be force-unwrapping sender like that. Instead, consider doing something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM