How to programmatically create and use a UIcollectionView?

I searched a lot to create a UICollectionView programmatically, but none of them suggested the easiest way to use it, how to add a label or image to a UICollectionViewCell . Most sites assume that the implementation of UICollectionView is the same as UITableView , but the main difference occurs when we try to add any image. In UITableView we can highlight imageViews in the cellForRow method, where cell == nil and assign images where ( cell != nil ). but here in the case of the UICollectionView ItemAtIndexPath method UICollectionView ItemAtIndexPath no condition ( cell == nil ), as in the UITableView cellForRow . As a result, we cannot efficiently distribute UImageView variables or shortcuts, etc. In the itemAtIndexPath method. I want to know if there is an alternative other than subclassing UICollectionViewCell and allocating variables in this custom class? Can anyone help, any help would be appreciated.

+6
source share
2 answers

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

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

here is the best link that I found useful. Hope this helps others

+3
source

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)") } 
+1
source

Source: https://habr.com/ru/post/978722/


All Articles