简体   繁体   English

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

[英]iOS Swift - UICollectionView - Sections different background color

Is there a way to set different background colors to UICollectionView's header and the content view? 有没有办法为UICollectionView的标题和内容视图设置不同的背景颜色?

I want my collection's header background color - clearColor and the content background to be white. 我希望集合的标题背景颜色为clearColor,内容背景为白色。

Thank you! 谢谢!

You can change the UICollectionViewCell background color within cellForItemAtIndexPath and the section header background within viewForSupplementaryElementOfKind 你可以改变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
    }

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM