2

I want to set up the collection view's header, and thus implemented the method func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView.

However, it seems that the switch statement does not work; even when I tried to set the label within the header view by branching off depending on the section, the resultant header view in all the sections has all the labels I wrote.

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    switch kind {
    case UICollectionElementKindSectionHeader:
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath)
        let headerLabel = UILabel(frame: CGRectMake(2, 8, 120, 24))
        headerView.addSubview(headerLabel)

        print(indexPath.section)
        switch (indexPath.section) {
        case 0:
            headerLabel.text = "A"
            return headerView
        case 1:
            headerLabel.text = "B"
            return headerView
        default:
            break
        }

        return headerView

    default:
        assert(false, "Unexpected element kind")
    }
}

In the above code, the both sections' label has both the label A and B, overlapped each other.

Why does the switch not work in my case?

The contents in my collection view fetch data from the server, and thus the print(indexPath.section) is executed 2 times, each printing out 0 and 1, in that order.

Is this related to the problem?

Blaszard
  • 30,954
  • 51
  • 153
  • 233

2 Answers2

1

You're adding a new label to the header view every time it is dequeued. You should have the label present already in the header (either as a prototype, xib file or created when a custom header class is initialised) and simply set the text each time in the method in your question.

If you can't do that, you need to check for the label's existence before creating it.

jrturton
  • 118,105
  • 32
  • 252
  • 268
-1

Case 1

I think you need to reload the collection view only after getting response from the server. And initialise the response/tableData array in view will appear.

Case 2

You can try with the response array data from server in switch condition.

sourav
  • 779
  • 5
  • 14