簡體   English   中英

將CollectionView添加為表視圖標題

[英]Add CollectionView as Table View Header

我想要展示這樣的橫幅:

在此輸入圖像描述

我的方法是將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!

}

在此輸入圖像描述

但我在標題上看不到那個圖像。 它只顯示一個空頭。

你使用NIB ,所以你應該使用func register(UINib?, forCellWithReuseIdentifier: String)而不是func register(AnyClass?, forCellWithReuseIdentifier: String)

也許你正在尋找像KIImagePager這樣的圖像尋呼機而不是集合視圖。 您也可以使用內置的PageViewController創建相同的內容。

您可以在此下方單獨添加TableView

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM