ios - 添加 CollectionView 作为 TableView 标题

标签 ios swift uitableview uicollectionview

我想展示这样的横幅:

enter image description here

我的方法是添加一个 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!

}

enter image description here

但我没有在标题中看到该图片。它只显示一个空标题。

最佳答案

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

关于ios - 添加 CollectionView 作为 TableView 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631466/

相关文章:

javascript - ontouchstart 在 iPad 上不可用?

swift - Swift 是否严格执行协议(protocol)变量中的类?

ios - 将现有的 objective-c 静态库转换为 swift

ios - objective-C : Issue faced while editing multiple row simultaneously in table view

ios - 无法分配值类型

ios - 难以处理 SQLite 中的编码

ios - 将分布在屏幕边缘的可移动 UILabel 保存到有序数组中

ios - SCNNode 释放具有更改的变换和枢轴属性的子节点

ios - 如何在一周中的特定一天但每隔一周运行一次通知(Swift + Xcode)?

ios - 如何为每个数组保存图像