Swift 实现自定义 UICollectionView的 section 背景

自定义 section 背景

首先创建一个 section装饰背景注册类, 内部包含一个 UIImageView, 可作为自定义背景填充视图

class SectionBackgroundReusableView: UICollectionReusableView {

    static let BACKGAROUND_CID = "BACKGAROUND_CID"

    private lazy var bgImageView = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self += bgImageView
    }

    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
        bgImageView.frame = bounds
        guard let att = layoutAttributes as? SectionDecorationViewLayoutAttributes else {
            return
        }
        backgroundColor = UIColor.clear
        bgImageView.layer.cornerRadius = 12.px
        bgImageView.clipsToBounds = true
        bgImageView.backgroundColor = att.backgroundColor
        bgImageView.setImage(url: att.imageName)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

之后定义一个 section装饰视图布局属性类

class SectionDecorationViewLayoutAttributes: UICollectionViewLayoutAttributes {

    // 装饰背景图片
    var imageName: String?

    // 背景色
    var backgroundColor = UIColor.white

    /// 所定义属性的类型需要遵从 NSCopying 协议
    /// - Parameter zone:
    /// - Returns:
    override func copy(with zone: NSZone? = nil) -> Any {
        let copy = super.copy(with: zone) as? SectionDecorationViewLayoutAttributes
        copy?.imageName = imageName
        copy?.backgroundColor = backgroundColor
        return copy as Any
    }

    /// 所定义属性的类型还要实现相等判断方法(isEqual)
    /// - Parameter object:
    /// - Returns: 是否相等
    override func isEqual(_ object: Any?) -> Bool {
        guard let rhs = object as? SectionDecorationViewLayoutAttributes else {
            return false
        }
        if imageName != rhs.imageName {
            return false
        }
        if !backgroundColor.isEqual(rhs.backgroundColor) {
            return false
        }
        return super.isEqual(object)
    }
}

之后我们自定义UICollectionViewFlowLayout

class SectionDecorationLayout: UICollectionViewFlowLayout {

    weak var decorationDelegate: SectionDecorationLayoutDelegate?

    /// 保存所有自定义的section背景的布局属性
    private var decorationBackgroundAttrs: [Int: UICollectionViewLayoutAttributes] = [:]

    override init() {
        super.init()
        // 背景View注册
        register(SectionBackgroundReusableView.self,
                 forDecorationViewOfKind: SectionBackgroundReusableView.BACKGAROUND_CID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 布局配置数据
    // swiftlint:disable cyclomatic_complexity
    // swiftlint:disable function_body_length
    override func prepare() {
        super.prepare()

        guard let collectionV = collectionView else {
            return
        }
        // 如果collectionView当前没有分区,则直接退出
        guard collectionV.numberOfSections != 0 else {
            return
        }
        // 不存在cardDecorationDelegate就退出
        guard let delegate = decorationDelegate else {
            return
        }
        if decorationBackgroundAttrs.isNonEmpty {
            decorationBackgroundAttrs.removeAll()
        }
        for section: Int in 0..<collectionV.numberOfSections {
            // 获取该section下第一个,以及最后一个item的布局属性
            let numberOfItems = collectionV.numberOfItems(inSection: section)
            guard numberOfItems > 0,
                  let firstItem = layoutAttributesForItem(at: IndexPath(item: 0, section: section)),
                  let lastItem = layoutAttributesForItem(at: IndexPath(item: numberOfItems - 1, section: section))
            else {
                continue
            }
            var sectionInset = sectionInset

            // 获取该section的内边距
            let inset = delegate.collectionView(collectionView: collectionV, layout: self, insetForSectionAt: section)
            if inset != .zero {
                sectionInset = inset
            }

            // 获取该section header的size
            let headerSize = delegate.collectionView(collectionView: collectionV,
                                                     layout: self,
                                                     headerForSectionAt: section)
            var sectionFrame: CGRect = .zero
            if scrollDirection == .horizontal {
                let hx = (firstItem.frame.origin.x) - headerSize.width + sectionInset.left
                let hy = (firstItem.frame.origin.y) + sectionInset.top
                let hw = ((lastItem.frame.origin.x) + (lastItem.frame.size.width)) - sectionInset.right
                let hh = ((lastItem.frame.origin.y) + (lastItem.frame.size.height)) - sectionInset.bottom
                sectionFrame = CGRect(x: hx, y: hy, width: hw, height: hh)
                sectionFrame.origin.y = sectionInset.top
                sectionFrame.size.width -= sectionFrame.origin.x
                sectionFrame.size.height = collectionV.frame.size.height - sectionInset.top - sectionInset.bottom
            } else {
                let vx = (firstItem.frame.origin.x)
                let vy = (firstItem.frame.origin.y) - headerSize.height + sectionInset.top
                let vw = ((lastItem.frame.origin.x) + (lastItem.frame.size.width))
                let vh = ( (lastItem.frame.origin.y) + (lastItem.frame.size.height) ) - sectionInset.bottom
                sectionFrame = CGRect(x: vx, y: vy, width: vw, height: vh + 10)
                sectionFrame.origin.x = sectionInset.left
                sectionFrame.size.width = collectionV.frame.size.width - sectionInset.left - sectionInset.right
                sectionFrame.size.height -= sectionFrame.origin.y
            }

            let attrs = SectionDecorationViewLayoutAttributes(
                forDecorationViewOfKind: SectionBackgroundReusableView.BACKGAROUND_CID,
                with: IndexPath(item: 0, section: section)
            )

            let backgroundColor = delegate.collectionView(collectionV,
                                                          layout: self,
                                                          decorationColorForSectionAt: section)
            attrs.frame = sectionFrame
            attrs.zIndex = -1
            attrs.backgroundColor = backgroundColor
            // 优先保存颜色
            decorationBackgroundAttrs[section] = attrs

            // 判断背景图片是否可见 不可见跳过
            let backgroundDisplayed = delegate.collectionView(collectionV,
                                                              layout: self,
                                                              decorationImageDisplayedForSectionAt: section)
            guard backgroundDisplayed else {
                continue
            }
            //  如果背景图片名称为nil,跳过
            guard let imageName = delegate.collectionView(collectionV,
                                                          layout: self,
                                                          decorationImageForSectionAt: section) else {
                continue
            }
            
            attrs.imageName = imageName

            let displayedFillet = delegate.collectionView(collectionV,
                                                          layout: self,
                                                          filletDisplayedForSectionAt: section)
            guard displayedFillet == false else {
                continue
            }
        }
    }
    // swiftlint:enable function_body_length
    // swiftlint:enable cyclomatic_complexity

    override func layoutAttributesForDecorationView(ofKind elementKind: String,
                                                    at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let section = indexPath.section
        if elementKind == SectionBackgroundReusableView.BACKGAROUND_CID {
            return decorationBackgroundAttrs[section]
        }
        return super.layoutAttributesForDecorationView(ofKind: elementKind,
                                                       at: indexPath)
    }

    /// 返回rect范围下父类的所有元素的布局属性以及子类自定义装饰视图的布局属性
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attrs = super.layoutAttributesForElements(in: rect)
        attrs?.append(contentsOf: decorationBackgroundAttrs.values.filter {
            rect.intersects($0.frame)
        })
        return attrs
    }
}

之后我们定义好给 layout 使用的 协议, 用来设置相关的属性

protocol SectionDecorationLayoutDelegate: NSObjectProtocol {

    /// Section背景的边距
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - layout: layout
    ///   - insetForSectionAtIndex: section
    /// - Returns: 边距
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets

    /// 获取 Section Header 宽高
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - layout: layout
    ///   - headerForSectionAtIndex: section
    /// - Returns: 宽高
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        headerForSectionAt section: Int) -> CGSize

    /// 获取 section footer 宽高
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - layout: layout
    ///   - footerForSectionAtIndex: section
    /// - Returns: 宽高
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        footerForSectionAt section: Int) -> CGSize

    /// 指定section的背景图片名字,默认为nil
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - collectionViewLayout: layout
    ///   - section: section
    /// - Returns: 图片字符
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        decorationImageForSectionAt section: Int) -> String?

    /// 指定section背景图的圆角,默认值为true
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - collectionViewLayout: layout
    ///   - section: section
    /// - Returns: 图片字符
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        filletDisplayedForSectionAt section: Int) -> Bool

    /// 指定section是否显示背景图片,默认值为false
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - collectionViewLayout: layout
    ///   - section: section
    /// - Returns: Bool
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        decorationImageDisplayedForSectionAt section: Int) -> Bool

    /// 指定section背景颜色,默认为白色
    /// - Parameters:
    ///   - collectionView: collectionView
    ///   - collectionViewLayout: layout
    ///   - section: section
    /// - Returns: UIColor
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        decorationColorForSectionAt section: Int) -> UIColor
}

最后就完成了section 背景的自定义, 把一个 collectionView 的分区自定义灵活设置背景

如何使用?

  1. 自定义 layout
private lazy var layout = SectionDecorationLayout().then {
        $0.minimumLineSpacing = 20.px
        $0.minimumInteritemSpacing = 0
        $0.decorationDelegate = self
        $0.sectionInset = UIEdgeInsets(top: 20.px, left: 20.px, bottom: 20.px, right: 20.px)
    }
  1. 引用 layout
private lazy var collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then {
        $0.backgroundColor = .clear
        $0.showsVerticalScrollIndicator = false
        $0.delegate = self
        $0.dataSource = self
        $0.registerCell(MineMedalListCell.self)
        $0.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20.px, right: 0)
        $0.registerHeader(MineMedalListHeaderView.self)
        $0.headerRefreshBlock = { [weak self] in
            guard let `self` = self else { return }
            self.viewModel.loadData(obtainType: self.obtainType)
            self.loadHeaderData()
        }
    }
  1. 代理方法
extension MedalListViewController: SectionDecorationLayoutDelegate {

    /// 是否显示单独设置 Section 背景颜色
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        decorationColorForSectionAt section: Int) -> UIColor {
        UIColor(0x444444)
    }

    /// 是否显示 Section 背景图
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        decorationImageDisplayedForSectionAt section: Int) -> Bool {
        true
    }

    /// 设置背景图的边距
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: 24.px, bottom: 0, right: 24.px)
    }

    /// 获取 Section Header 宽高 (设置section背景图是否占据头的size)
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: SectionDecorationLayout,
                        headerForSectionAt section: Int) -> CGSize {
        CGSize(width: UIScreen.width, height: 90.px)
    }

详细如图


截屏2022-06-22 下午5.58.12.png

图片中只用了纯黑灰色背景, 以上代码还可以配置背景的图片.

以上.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,561评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,218评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,162评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,470评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,550评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,806评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,951评论 3 407
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,712评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,166评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,510评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,643评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,306评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,930评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,745评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,983评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,351评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,509评论 2 348

推荐阅读更多精彩内容