简体   繁体   中英

Pass Data from UICollectionView in Swift 2

My problem is I would like to Pass data from my collection view to a new view (tableview- but I think it's not necessary info)

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let myVC = DetailsTableViewController()
    myVC.movieTitle = movies[indexPath.row].movieTitle!
    print (movies[indexPath.row].movieTitle!)
    performSegueWithIdentifier("DetailSegue", sender: reuseIdentifier)
}

Print is OK, but my movieTitle: String? will NIL on the DetailsViewController.

Help!

performSegueWithIdentifier will instantiate an appropriate destination controller and present it. The DetailsTableViewController you have instantiated here as myVC is never shown. You have a couple of options for how to approach this:

If you want to use segues then trigger the segue in didSelectItemAtIndexPath and implement prepareForSegue to pass data to the destination view controller (a destinationViewController will be available on the UIStoryboardSegue passed to that method).

Alternately you could avoid using segues and present your myVC directly by pushing it onto your current navigation controller (if one exists you could call self.navigationController.pushViewController(myVC, animated:true) ), presenting it as a modal, or whatever makes sense in your app.

problem solved. thanks

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "DetailSegue" {
        let detailsVC = segue.destinationViewController as! DetailsTableViewController
        if let cell = sender as? UICollectionViewCell, indexPath = collectionView!.indexPathForCell(cell) {
    // use indexPath
            detailsVC.movieTitle = movies[indexPath.row].movieTitle!
        }
    }
}

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