iOS Swift - segue to a class - passing Int value from a ViewController to a Class using prepareForSegue

时间:2015-09-01 22:16:57

标签: ios swift

I am trying to push value of variable cellNumber located in ViewOne (ViewController) to variable trackNumber located at RadioPlayer (class RadioPlayer) buy using below code in ViewOne:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    //var DestViewControler : ViewController = segue.destinationViewController as! ViewController
    var Dest2ViewControler : RadioPlayer = segue.destinationViewController as! RadioPlayer

   // DestViewControler.trackNumber = cellNumber
    Dest2ViewControler.trackNumber = cellNumber
}

but I am getting bellow error when running the app:

 Could not cast value of type 'The_Radio_App.ViewController' (0x73e48) to 'The_Radio_App.RadioPlayer' (0x745a8).

and this line of code is highlighted in green: var Dest2ViewControler : RadioPlayer = segue.destinationViewController as! RadioPlayer

So I think what is causing a problem here is this: segue.destinationViewController - because RadioPlayer is not a ViewController but just a class. How can I amend this to make this work?

2 个答案:

答案 0 :(得分:2)

The error indicates the segue.destinationViewController is an object of type ViewController not of type RadioPlayer. As a result, your forced cast is causing a crash, because you are making an incorrect assertion to the compiler.

In your storyboard, go to scene representing the destination of this segue. Go the identity inspector for the view controllor of that scene. (Select the yellow box in the storyboard to select the VC, and then check the 2nd or 3rd item in the right panel.) Make sure that the field defining the class says "RadioPlayer".

答案 1 :(得分:0)

Try this:

let dest2ViewControler = segue.destinationViewController as! Dest2ViewController

destViewControler.radioPlayer.trackNumber = cellNumber

Where radioPlayer is the RadioPlayer member variable in your Dest2ViewController class