我正在尝试使用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/