Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 517
Mounika Vangala Avatar asked Nov 26 '14 11:11

Mounika Vangala


2 Answers

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

like image 154
Mounika Vangala Avatar answered Nov 09 '22 23:11

Mounika Vangala


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)")
   }
like image 27
Tanvir Nayem Avatar answered Nov 09 '22 23:11

Tanvir Nayem