如何在Swift中添加UICollectionView的页眉和页脚视图

时间:2015-12-15 05:59:02

标签: ios swift uicollectionview

我在控制器类中添加了委托函数,但在运行时不会调用它。

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
}

4 个答案:

答案 0 :(得分:9)

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionElementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath) as! UICollectionReusableView

        headerView.backgroundColor = UIColor.blueColor();
        return headerView

    case UICollectionElementKindSectionFooter:
        let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Footer", forIndexPath: indexPath) as! UICollectionReusableView

        footerView.backgroundColor = UIColor.greenColor();
        return footerView

    default:

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

答案 1 :(得分:4)

我按照本教程Appcoda tutorial更新代码以获取swift 4.0

注册课程:

self.collectionView.register(HeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeadView")

代表:

// For header size (required)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width:collectionView.frame.size.width, height:50.0)
}


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

    switch kind {

    case UICollectionElementKindSectionHeader:

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

        headerView.backgroundColor = UIColor.blue;
        return headerView

    default:

        fatalError("Unexpected element kind")
    }
}

答案 2 :(得分:3)

未调用Delegate方法,因为您需要为补充视图注册一个类;

yourCollectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionHeaderID")

yourCollectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "collectionFooterID")

答案 3 :(得分:2)

如果您使用Custom UICollectionViewFlowLayout

设置headerReferenceSize

let flowLayout = UICollectionViewFlowLayout()
    flowLayout.scrollDirection = .vertical
    flowLayout.minimumLineSpacing = 0
    flowLayout.minimumInteritemSpacing = 0
    flowLayout.sectionHeadersPinToVisibleBounds = true
    flowLayout.headerReferenceSize = CGSize(width:      self.collectionView.frame.size.width, height: 50)