Why my cellForItemAtIndexPath doesn't works but numberOfItemsInSection works better in swift?

442 Views Asked by At

I am trying to make UICollection view programmatically, actually I already made 2 UICollection using storyboard successfully but the third I want to make it programmatically and it seems doesn't works well, I already did UICollectioanViewCell with the name TesCollectionViewCell. cellForItemAtIndexPath doesn't works but oddly the numberOfItemsInSection works better

Here my code :

class TesCollectionView: UIControl,  UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
var uiCollectionView : UICollectionView
var collHuh = ["Happy", "Feet", "Cool"]

override init(frame: CGRect)
{
    println("heyyyyyyyyyy")
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .Horizontal
    layout.itemSize = CGSize(width: 150, height: 150)

    uiCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
    uiCollectionView.registerClass(TesCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")


    super.init(frame: frame)

    uiCollectionView.dataSource = self
    uiCollectionView.delegate = self

    addSubview(uiCollectionView)


    layer.borderWidth = 2



}



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{println("Does works better")
    return 10
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{ println("it works now")
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! TesCollectionViewCell
    cell.imageView.image = UIImage(named: "image")
    cell.backgroundColor = UIColor.blueColor()
    return cell

}

required init(coder aDecoder: NSCoder)
{
    uiCollectionView = UICollectionView(frame: CGRectZero)
    super.init(coder: aDecoder)
}

}

What's wrong with my code?

2

There are 2 best solutions below

2
On BEST ANSWER

make sure your cell frame size not 0,0!

func collectionView(collectionView: UICollectionView,
  layout collectionViewLayout: UICollectionViewLayout,
  sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

  return CGSize(width: 100, height: 100)
}
0
On

Set number of items in section.

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int?