Swift collectionViewCells are not showing

2019-03-04 00:02发布

I have got this Swift code `

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

` But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

4条回答
够拽才男人
2楼-- · 2019-03-04 00:25

You have to provide the size for collection view cell. add the below code snippet

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // calculate and return the height
}
查看更多
别忘想泡老子
3楼-- · 2019-03-04 00:26

In your cellForItemAt dataSource method you need to give custom UICollectionCell Class

let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell

Then you will able to see cell.

查看更多
够拽才男人
4楼-- · 2019-03-04 00:37

Try This code:

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 60, height: 60)

    let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    myCollectionView.dataSource = self
    myCollectionView.delegate = self
    myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    myCollectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(myCollectionView)
查看更多
闹够了就滚
5楼-- · 2019-03-04 00:38

Try it. You add in the class

UICollectionViewDataSource and UICollectionVIewDelegate.
查看更多
登录 后发表回答