WepsTech
The world of development
Hello Guys, Welcome to this tutorial. I hope you are doing well. Here once again I came with a new wonderful tutorial. Which is as How to use UICollectionView in iOS with Swift. In this tutorial, I will make you understand about the UICollectionView usage. Here I will make clear each and everything with the help of a basic example.
Let’s move towards with the practice. I hope you are ready now. Please follow the below steps.
import UIKit class ExampleCell: UICollectionViewCell { @IBOutlet weak var img: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var des: UILabel! }
Wonderful, You have done upto now. Now it’s time to update your view controller as given below.
import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self setCollectionView() } func setCollectionView(){ let flowLayout = UICollectionViewFlowLayout() //SINGLE ITEM IN CELL //flowLayout.itemSize = CGSize(width: collectionView.frame.width, height: collectionView.frame.height) // DOUBLE ITEM IN CELL flowLayout.itemSize = CGSize(width: collectionView.frame.width/2 - 2.5, height: collectionView.frame.width/2) flowLayout.minimumLineSpacing = 5 flowLayout.minimumInteritemSpacing = 5 flowLayout.scrollDirection = .vertical collectionView.setCollectionViewLayout(flowLayout, animated: true) } } extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 40 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ExampleCell cell.title.text = "Title : \(indexPath.row + 1)" cell.contentView.backgroundColor = .black return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("ITEM SELECTED : \(indexPath.row + 1)") } }
Wonderful, In Conclusion , I hope it is bit clear to you. But if you still confuse then go through with video.
If you are looking for more topic then please check once below links