我以编程方式创建了一个collectionView(没有故事板)。我将背景颜色设置为红色,它显示正常。但是单元格没有显示。有人知道为什么单元格没有显示吗?
private let cellId = "cellId"
class InfoViewShow: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let cellHeight:CGFloat = 80
var collectionView: UICollectionView?
let layout = UICollectionViewFlowLayout()
override init() {
super.init()
setupCollectionview()
collectionView?.registerClass(InfoCell.self, forCellWithReuseIdentifier: cellId)
}
private func setupCollectionview() {
if let view = UIApplication.sharedApplication().keyWindow {
//let y = (view.frame.width * 10 / 16) + 34 + 26
collectionView = UICollectionView(frame: .zero , collectionViewLayout: layout)
collectionView?.backgroundColor = UIColor.redColor()
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.frame = CGRectMake(0, 0, view.frame.width, view.frame.height) // y to y
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath)
cell.backgroundColor = UIColor.blackColor()
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.frame.width, cellHeight)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
}
}
2条答案
按热度按时间ccrfmcuu1#
我没有看到您将
collectionView
添加到视图中。xmakbtuz2#
您必须实作
UICollectionViewDataSource
委派方法的numberOfSectionsInCollectionView
。这个方法是选择性的,但您必须实作它并至少传回一个区段。