我正试图将indexpath处的值传递给下一个视图控制器,但我不确定如何做到这一点。
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
}
这里是resultResponse,它在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?
}
您应该创建一个类型为"resultResponse";在DestVC中。
示例:
class DestVC: UIViewController {
var filered: resultResponse?
}
在CollectionView中,您只需要传递filterd变量。它使您的代码变得干净。你应该使用";如果让"以确保您的应用程序不会在数据为零时崩溃
示例:
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
}