user11100093
user11100093

Reputation:

Show 3 images on 1st row and 3 images on second row on collectionview

I dragged a collectionview on to my xib, set the constraints as leading,trailing,top and height.

The coding part is given as...

 override func viewDidLoad() {
    super.viewDidLoad()
           let layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 5
    layout.minimumInteritemSpacing = 5

    collectionview2.delegate = self
    collectionview2.dataSource = self
    collectionview2.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ident")

    }
  }


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


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
 switch indexPath.item {
      case 0,1:
        return CGSize(width: (UIScreen.main.bounds.width - 16) / 2, height: (UIScreen.main.bounds.width - 16) / 2)
      default:
        return CGSize(width: (UIScreen.main.bounds.width - 32) / 3, height:  (UIScreen.main.bounds.width) / 3)
      }
}



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ident", for: indexPath)
      cell.backgroundColor = .red
      return cell

}

This is the link I have referred. But it is not working and I'm seeing just 5 equal width and height cells one after the other.

What am I doing wrong...?

EDIT 1: I would also like to show one long cell on left and 2 small cells on right like so...

What changes do I make to my answer so that I can achieve this...? enter image description here

Upvotes: 0

Views: 552

Answers (1)

Ahemadabbas Vagh
Ahemadabbas Vagh

Reputation: 494

Your code looks perfect but you may forgot to confirm the FlowLayout Protocol. so, you just need to confirm the below protocol in your code,

UICollectionViewDelegateFlowLayout

Hope this way may help you.

Upvotes: 1

Related Questions