Mounika Vangala
Mounika Vangala

Reputation: 396

How to create and use UIcollectionView programmatically?

I have searched a lot for creating a UICollectionView programatically but none of them suggest the simplest way to use it, how to add a label or an image to the UICollectionViewCell. Most of the sites suggest that implementation of UICollectionView is same as UITableView, but the major difference comes when we try to add any image. In UITableView we can allocate the imageViews in cellForRow method where cell == nil and assign images where (cell != nil). but here in case of UICollectionView ItemAtIndexPath method, there is no condition (cell == nil) as in UITableView's CellForRow. As a result we can't effectively allocate variables of UImageViews or Labels etc in itemAtIndexPath method. I Want to know whether there is any alternative other than subclassing the UICollectionViewCell and allocating variables in that custom Class? Can any one help, any help is appreciated.

Upvotes: 6

Views: 25884

Answers (2)

Mounika Vangala
Mounika Vangala

Reputation: 396

There is not alternative to create or allocate cells in itemAtIndex method. We need to register the customised class to create any views inside the custom class. something like this :

[UICollectionView registerClass:[CustomCollectionViewClass class] forCellWithReuseIdentifier:@"cellIdentifier"];

here is the best link which I found useful. Hope it helps others

Upvotes: 2

Tanvir Nayem
Tanvir Nayem

Reputation: 722

swift :

   override func viewDidLoad() {
       super.viewDidLoad()

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

       let demoCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
       demoCollectionView.dataSource = self
       demoCollectionView.delegate = self
       demoCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
       demoCollectionView.backgroundColor = UIColor.whiteColor()
       self.view.addSubview(demoCollectionView)
   }

   func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return 27
   }

   func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
       cell.backgroundColor = UIColor.lightGrayColor()
       return cell
   }

   func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
  {
       print("User tapped on item \(indexPath.row)")
   }

Upvotes: 1

Related Questions