jbehrens94
jbehrens94

Reputation: 2406

CollectionView in ScrollView

I am working on an iOS app where I want to show a UIScrollView with two UILabels an UIImageView and a UICollectionView at the bottom. Now I don't know how to do this in auto layout, who could help me out?

I've tried just adding everything and setting the constraints to each other, but I do remember that the UIScrollView needs to calculate the intrinsic content height. How can I create this scroll view?

Upvotes: 1

Views: 2751

Answers (1)

nils
nils

Reputation: 1976

I would avoid embedding the UICollectionView into a UIScrollView in this case. It will be easier to add the UILabels and UIImageView into a section header using a UICollectionReusableView subclass.

Here are the steps:

  1. Add a section header to the UICollectionView:

enter image description here

  1. Create your section header view class by subclassing UICollectionReusableView. Set custom class and reuse identifier of the header reusable view:

enter image description here enter image description here

  1. Lay out your header view. Connect your outlets.
  2. Implement the viewForSupplementaryElementOfKind method.

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
        // If you also use footers:
        // use a switch statement on the 'kind' argument to
        // decide which view to dequeue.
    
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
    
        // set up your header view
    
        return view
    }
    

Upvotes: 3

Related Questions