UICollectionview header implementation iOS swift

 Problem:

I want to add header like tableview view to show the title of the section in UICollectionview iOS swift


Solution:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        let indexPath = IndexPath(row: 0, section: section)

        let headerView = self.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader, at: indexPath)

        

        return headerView.systemLayoutSizeFitting(CGSize(width: collectionView.frame.width, height: UIView.layoutFittingExpandedSize.height),

                                                  withHorizontalFittingPriority: .required, // Width is fixed

                                                  verticalFittingPriority: .fittingSizeLevel)

    }

    

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath) asHeaderCell

        

        switch kind {

        case UICollectionView.elementKindSectionHeader:

                headerView.title.text = "header"

            

            return headerView

            

        default:

            assert(false, "Unexpected element kind")

        }

        

        return headerView

    }

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift