【发布时间】:2017-05-11 10:08:41
【问题描述】:
我在基本 ViewController 中实现 UICollectionView (collectionView) 我的集合视图必须检索 5 个单元格,如 numbersofItemInSection 代码。 显示 CollectionView 并调用 numbersofItemInSection 函数,但未调用 cellForItemAt 函数,因此集合视图为空。
import UIKit
private let reuseIdentifier = "Cell"
class TestViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.delegate = self
cv.dataSource = self
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.backgroundColor = .white
navigationItem.title = "test"
setupViews()
}
func setupViews(){
view.addSubview(collectionView)
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
collectionView.heightAnchor.constraint(equalToConstant: 60).isActive = true
collectionView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
cell.backgroundColor = .red
return cell
}
}
【问题讨论】:
-
它确实按预期工作。 imgur.com/a/IYslT
-
你用过 xib 的 cell 吗?
-
@SaurabhYadav 这可能是我的 Xcode 设置吗?因为我昨天安装了 Xcode 7,所以我现在有 2 个 Xcode 应用程序。
-
@KKRocks 不,我没有使用 xib。只是 UICollectionViewCell 本身。
-
它与 stroyboard 中的 viewcontroller 一致吗?
标签: ios swift uicollectionview uicollectionviewcell