我想要展示这样的横幅:
我的方法是添加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)