ios - 未调用 UICollectionView 方法(collectionView cellForItemAt indexPath)

标签 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")
    }
}

最佳答案

请检查:

您的布局应如下所示。

您使用了 UICollectionViewLayout

你必须使用UICollectionViewFlowLayout

let layout = UICollectionViewFlowLayout()

关于ios - 未调用 UICollectionView 方法(collectionView cellForItemAt indexPath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46497404/

相关文章:

ios - UICollectionView 单元格不并排

具有动态单元高度的 Swift 水平 UICollectionView

ios - 将它用作输入 View 时从 UIPickerView 获取 UITextField

ios - 如何在 tableview 中添加额外的行,除了 swift 中的两个单元格

ios - 下载外部网页,用js和css修改,然后加载到 View 中的最佳方法

iphone - GLfloat 动态数组声明

ios - UItableView 显示重复的单元格,我的数据有什么问题吗?

ios - 如何更改UISegmentedControl的单个索引的字体大小?

ios - WatchKit XCODE 6.3 问题

ios - NSTimeZone和特殊时区等