未调用 UICollectionView cellForItem

UICollectionView cellForItem not called

我正在基本 ViewController 中实现 UICollectionView (collectionView) 我的集合视图必须像 numbersofItemInSection 代码中那样检索 5 个单元格。 显示 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
    }


}

是你的collectionView的高度或者collectionView的frame问题,那么你需要给collectionView设置合适的高度。

试试这个

     override func viewDidLoad() {
                super.viewDidLoad()
                navigationItem.title = "test"

                setupViews()
                collectionView.backgroundColor = .white
                self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 
// remove this line if you not use xib

            }

我检查了你的代码,它正在工作 fine.As 你正在使用 swift 3 所以你将不得不使用 xCode 8+.运行 它与 XCODE 8,因为语法是 swift 3,你会得到结果。