考虑到您没有在cellForItemAt indexPath 中显示您使用的单元格类型,因此我不得不编造一些事情,这样您就可以清楚地了解这一点。我也不知道你有 4 个集合视图是什么意思,但这是使用 1 个集合视图通过 prepareForSegue 将数据从 collectionViewCell 传输到目标视图控制器的方式之一。
在preparForSegue 里面你需要三样东西:
1- 您需要知道您在cellForItemAt indexPath 中使用的单元格类型。对于这个例子,我使用了一个名为 MovieCell
的单元格类
2- 您需要获取所选行的 indexPath。 CollectionView 上有一个名为 indexPath(for:) 的方法,它接受一个 collectionViewCell 作为参数:collectionView.indexPath(for: UICollectionViewCell)
3- 从与所选行对应的数组中获取信息。
例如,您有一个名为 MovieDataModel 的类,其中包含一个 movieName 属性:
class MovieDataModel{
var movieName: String?
}
collectionView 单元名为 MovieCell,其中有一个 movieTitleLabel 插座:
class DetailedSearchComplaintCollectionCell: UICollectionViewCell {
@IBOutlet weak var movieTitleLabel: UILabel!
}
在你的 CollectionView 类中:
@IBOutlet weak var collectionView: UICollectionView! // in this example there is only 1 collectionView
let movies = [MovieDataModel]() // an array of MovieDataModels
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies.count // return the number of items inside the movies array
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as! MovieCell // cast the cell as a MovieCell
cell.movieTitleLabel.text = movies[indexPath.row].movieName! // this is the same info we need for the 3rd step
return cell
}
// sender parameter <<<
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "MovieDetailsPlaying"){
// From the steps above
let cell = sender as! MovieCell // 1- the same exact type of cell used in cellForItemAt indexPath. Access it using the sender parameter in the prepareFoeSegue signature and then cast it as a MovieCell
let indexPath = collectionView.indexPath(for: cell) // 2- get the indexPath from the row that was tapped. Add the cell from step 1 as an argument to it. Notice it says collectionView because that's the name of the collectionView outlet. I'm not sure how this would work with 4 different collectionViews but you probably will have to make an indexPath for each one. Just an assumption
var destination = segue.destination as! DetailMovieController
destination.item = movies[indexPath!.row].movieName // 3- what MoviesDataModel item from inside the movies array and the title from it corresponds to the indexPath (the tapped row).
}
}
我不知道您使用的 collectionView 单元格的名称,但在带有 collectionView 的类中,无论您在何处看到 MovieCell 名称,只需将其更改为您使用的单元格名称即可。