swift-UICollectionView添加頭視圖(返回圖片文字xib等)

給每組的頭部返回指定類型視圖

1.設置組頭的大小

layout.headerReferenceSize = CGSize(width: 375, height: 160)

2.註冊:

返回的是 UICollectionReusableView
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "kHeaderViewID")

返回的是xib
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "kHeaderViewID")

3.實現數據源


返回非xib
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //1.取出section的headerView
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "kHeaderViewID", for: indexPath) as UICollectionReusableView
        let headerImg = UIImageView(image: UIImage(named: "pt_header_bg"))
        headerImg.frame = CGRect(x: 0, y: 0, width: XMM_ScreenWidth, height: XMM_GetScaleValue(150))
        headerView.addSubview(headerImg)
        return headerView
    }
返回xib

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //1.取出section的headerView
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "kHeaderViewID", for: indexPath)
        return headerView
    }

筆記:
想給組頭返回什麼東西,應該首先考慮的是返回的類型是什麼 ,collectionView中返回給組頭的是 UICollectionReusableView 這是什麼東西,看源碼發現是UIView 那就好辦了,UIView 是有一個addSubview 方法的,那想要返回什麼直接添加到裏面就好,另外deq方法後面是需要加as 的,as 的意思就是類型轉換爲什麼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章