Chris Mikkelsen
Chris Mikkelsen

Reputation: 4067

How to display multiple sections in UICollectionView

Collection view only shows the first section, but doesn't show the second section.

Here are the delegates

private func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int {
    return 2
}

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

    var returnValue = Int()

    if section == 0 {
        returnValue = 1

    } else if section == 1 {
        returnValue = self.section1DataSource.count

    }

    return returnValue

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell = UICollectionViewCell()

    let cellA:GroupPhoto = collectionView.dequeueReusableCell(withReuseIdentifier: "groupPhotoCard", for: indexPath) as! GroupPhoto
    let cellB:AddFriendCell = collectionView.dequeueReusableCell(withReuseIdentifier: "addFriendCard", for: indexPath) as! AddFriendCell

    let section = indexPath.section

    if section == 0 {

        cell = cellA

    //end of section 0
    } else if section == 1 {
        cell = cellB
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    var returnValue = CGSize()

    if indexPath.section == 0 {

        returnValue = CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.height / 3.0 - 8)

    } else if indexPath.section == 1 {
        returnValue = CGSize(width: collectionView.frame.size.width / 2.9 - 8, height: collectionView.frame.size.height / 2.9 - 8)
    }

    return returnValue
}

When I interchange the conditions so that the first section's cell will be assigned to the second section. It works fine, but it will still only show the first section and not the second.

Upvotes: 6

Views: 18522

Answers (2)

In swift 3, numberOfSectionsInCollectionView is changed to numberOfSections(in:)

To avoid this, you should add UICollectionViewDataSource, to implement autocomplete.

Upvotes: 3

Nirav D
Nirav D

Reputation: 72410

Signature of numberOfSections(in:) is changed in Swift 3 it should be like this.

func numberOfSections(in collectionView: UICollectionView) -> Int { 
    return 2 
}

Upvotes: 17

Related Questions