未调用UICollectionView方法(collectionView cellForItemAt indexPath)

时间:2017-09-29 21:55:27

标签: ios swift xcode uicollectionview uicollectionviewcell

我正在尝试使用UICollectionView创建自定义栏菜单,问题是单元格未显示方法collectionView cellForItemAt indexPath未调用。

到目前为止我的代码:

import UIKit
private let reuseIdentifier = "Cell"

class MenuBar : UIView ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

   lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewLayout()
        let cv = UICollectionView(frame: .zero , collectionViewLayout : layout)
        cv.dataSource = self
        cv.delegate = self
        cv.backgroundColor = UIColor.white
        return cv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        addSubview(collectionView)
        setUpCollectionViewConstraints()
    }

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
        cell.backgroundColor = UIColor.red

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: frame.height/2, height: frame.height)
    }

    fileprivate func setUpCollectionViewConstraints() {
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["cv" : collectionView])
        let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat:"V:|[cv]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["cv" : collectionView])
        addConstraints(horizontalConstraints)
        addConstraints(verticalConstraints)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

2 个答案:

答案 0 :(得分:2)

请检查:

您的布局应如下所示。

您使用了UICollectionViewLayout

您必须使用UICollectionViewFlowLayout

let layout = UICollectionViewFlowLayout()

答案 1 :(得分:0)

看起来数据源出错了。

您的 MenuBar 是否在 ViewController 上?

您可能无法将collectionView的数据源设置为 MenuBar 代理)。您可以将collectionView的数据源设置为 ViewController

希望这个建议可以帮到你。