iosswifticarousel

How to pass image/data to new view controller from iCarousel


I have an iCarousel set up in one of my view controllers, and I would like to simply pass the same image that the user taps onto the next view controller. Here is what I have in my prepareForSegue on the Carousel VC:

 var padIndex = [UIImage]()

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {



   let nextVC = segue.destination as! BlackViewController

   let indexPath = sender as! NSIndexPath

    nextVC.pad = self.images[indexPath.row]
}

Then in my secondVC I have:

var pad = UIImage()

@IBOutlet weak var padImage: UIImageView!

 override func viewDidLoad() {
    super.viewDidLoad()

     padImage.image = pad
}

Seems like a simple thing, but I keep getting an error that says:

Could not cast value of type 'SampleSequencer.ChooseViewController' (0x10213fe38) to 'NSIndexPath' (0x1025b8440).

Thanks a billion in advance!!


Solution

  • The exception is telling you that you've got an illegal cast. The error is here:

    let indexPath = sender as! NSIndexPath

    The sender argument of prepare(for:sender:) says that it can be Any?, but in reality, it's not terribly useful because you can't be sure what it's going to be. You have to get the IndexPath from the iCarouselDelegate (which is probably your own view controller, if it implements iCarouselDelegate), using the delegate's carousel(_:,didSelectItemAtIndex:) method.