简体   繁体   中英

Passing a value at indexPath in collectionView

I'm trying to pass the value at the indexpath to the next view controller but I'm unsure on how to do that.

var imageStore =  [Data]()
var imageStoreReference = [(resultResponse, Data)]()


 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let DestVC = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        let filtered = imageStoreReference.filter({imageStore.contains($0.1)}).first
        DestVC.createdAt = filtered?.0.createdAt
        DestVC.Imagedescription = filtered?.0.description
        DestVC.instagram = filtered?.0.user.instagram
        DestVC.twitter = filtered?.0.user.twitter
        DestVC.portfolio = filtered?.0.user.portfolio
        DestVC.fullImage = filtered?.0.urls.regular
        DestVC.userProfileImage = filtered?.0.user.profileImageUrl.regular
}

Here is resultResponse, that is referenced in the tuple of imageStoreReference.

struct resultResponse: Codable {
    let createdAt: String
    let description: String?
    let urls: urlResponse
    let user: userResponse
  }

struct urlResponse: Codable {
    let regular: String
    let small: String
}

struct userResponse: Codable {
    let instagram: String?
    let twitter: String?
    let name:String?
    let portfolio: String?
    let profileImageUrl: imageSize
    
    enum CodingKeys: String, CodingKey {
        case instagram = "instagram_username"
        case twitter = "twitter_username"
        case profileImageUrl = "profile_image"
        case name
        case portfolio = "portfolio_url"
    }
}

struct imageSize: Codable {
    let regular: String?
}

You should create a variable which has type as "resultResponse" in DestVC.

Example:

class DestVC: UIViewController {
    var filered: resultResponse?
}

In CollectionView you need only pass filtererd variable. It make your code clean. And you should use "if let... " to ensure your app cant crash when data nil

Example:

var imageStore =  [Data]()
var imageStoreReference = [(String, Data)]()


 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let DestVC = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
    if let index = imageStoreReference.firstIndex(where: { (image) -> Bool in
        imageStore.contains(image.1)
    })
        let filtered = imageStoreReference[index]
        DestVC.filtered = filtered
}

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