【发布时间】:2018-11-30 16:56:30
【问题描述】:
我正在尝试使用UICollectionView,它显示在视图上,但没有调用委托方法。这是我正在尝试做的事情:
在 Storyboard 上,我有一个 UITableViewController,其中有一个 TableView 和一个 UIView,如下所示:
我在UITableViewController 班级上为UIView 创建了一个出口:
class FeedTableViewController: UITableViewController {
@IBOutlet weak var bannerView: UIView!
}
在viewDidLoad() 函数上,我正在实例化UIViewController 类,它将成为我的UICollectionView 的委托和数据源:
override func viewDidLoad() {
let bannerViewController = BannerViewController()
bannerView.addSubview(bannerViewController.view)
bannerViewController.view.translatesAutoresizingMaskIntoConstraints = false
bannerViewController.view.leadingAnchor.constraint(equalTo: bannerView.leadingAnchor).isActive = true
bannerViewController.view.trailingAnchor.constraint(equalTo: bannerView.trailingAnchor).isActive = true
bannerViewController.view.topAnchor.constraint(equalTo: bannerView.topAnchor).isActive = true
bannerViewController.view.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor).isActive = true
}
这是BannerViewController类的完整代码:
class BannerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 125)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .cyan
view.addSubview(collectionView)
}
}
extension BannerViewController: UICollectionViewDataSource {
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
cell.backgroundColor = .red
return cell
}
}
extension BannerViewController: UICollectionViewDelegateFlowLayout {
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
}
}
UICollectionView 正在被实例化并出现在视图中,正如我们在此处的青色框上看到的那样:
但是没有调用委托方法numberOfItemsInSection 和cellForItemAt。而且我已经将BannerViewController注册为UICollectionView的数据源和委托,所以我不知道为什么它不起作用。
【问题讨论】:
标签: ios swift uicollectionview uikit