swift2 UICollectionView正在显示,但单元格未在swift中显示

rur96b6h  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(192)

我以编程方式创建了一个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
}
}
ccrfmcuu

ccrfmcuu1#

我没有看到您将collectionView添加到视图中。

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

        ///try add
        self.view.addSubview(collectionView)
    }
xmakbtuz

xmakbtuz2#

您必须实作UICollectionViewDataSource委派方法的numberOfSectionsInCollectionView。这个方法是选择性的,但您必须实作它并至少传回一个区段。

相关问题