UICollectionView标头中的标题显示不正确

时间:2019-05-17 07:42:48

标签: swift uicollectionview header

我正在做电影应用程序,并且标题(电影类别)在UICollectionView标头中显示不正确。代替“冒险”,它在所有类别中显示“卡通”。 viewForSupplementaryElementOfKind方法有什么问题?

以下是一些代码:

struct MovieCategory {

    let title: String
    let img: String

}
     

DataSet类{

let categories = [MovieCategory(title: "Cartoons",     img:"coco1.jpg"),
                  MovieCategory(title: "Adventure", img: "lord.jpg"),
                  MovieCategory(title: "Drama", img: "titanic.jpg")]

}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

            switch kind {
            case UICollectionElementKindSectionHeader:

                let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCollection", for: indexPath) as! HeaderCollectionReusableView

                headerView.headerLebel.text = myData.categories[indexPath.row].title

                return headerView

            default: assert(false, "Error")

            }

        }

以下是一些屏幕截图:[1]:https://i.stack.imgur.com/oIy4w.jpg,[2]https://i.stack.imgur.com/6XAOH.jpg

1 个答案:

答案 0 :(得分:0)

您在每个标头中传递了indexPath.row,这是错误的。使用indexPath.section代替

headerView.headerLebel.text = myData.categories[indexPath.section].title