iOS Swift - UICollectionView - 部分不同的背景颜色

时间:2016-02-22 15:35:04

标签: ios swift background header uicollectionview

有没有办法为UICollectionView的标题和内容视图设置不同的背景颜色?

我想要我的集合的标题背景颜色 - clearColor和内容背景为白色。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以更改UICollectionViewCell中的cellForItemAtIndexPath背景颜色和viewForSupplementaryElementOfKind

中的部分标题背景
override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = UIColor.magentaColor()
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.whiteColor()
            return cell
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return   2
    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 10
    }

    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath)
        if kind == UICollectionElementKindSectionHeader {
            headerView.backgroundColor = UIColor.clearColor()
        }
        return headerView
    }

enter image description here