Я хочу показать баннер, как это:Добавить CollectionView в Table View Заголовок
Мой подход добавляет CollectionView
в виде TableViewHeader
Мой код:
extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func configureHeaderView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let headerView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: headerHeight), collectionViewLayout: layout)
headerView.backgroundColor = .blue
headerView.isPagingEnabled = true
headerView.isUserInteractionEnabled = true
headerView.dataSource = self
headerView.delegate = self
headerView.register(BannerCollectionViewCell.self, forCellWithReuseIdentifier: BannerCollectionViewCell.reuseIdentifier)
headerView.showsHorizontalScrollIndicator = false
tableView.tableHeaderView = headerView
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BannerCollectionViewCell.reuseIdentifier, for: indexPath) as! BannerCollectionViewCell
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: headerHeight)
}
}
Мои BannerCollectionViewCell
имеет изображение по умолчанию.
class BannerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var bannerImageView: UIImageView!
}
Но я не вижу, что изображение на моем заголовке. Он просто показывает пустой заголовок.
Вы пробовали использовать метод делегата 'viewForHeaderInSection'? –
Пока нет, я установил 'tableView.tableHeaderView = headerView', эквивалентны ли они друг другу? – Khuong
в 'cellForItemAt indexPath', вам нужно установить изображение. например 'cell.imageView.image =" abc.png "' –