给UICollectionView设置组背景和组圆角-Swift
钟情圆角怎么办?
最近由于我们的UI设计钟情于圆角搞得我很方,各种圆角渐变,于是就有了下面这篇给UICollectionView的组设置圆角和背景色的一个小封装,拿出来和大家分享一下,里面的具体的一下细节都在代码注释里面,大家留意下代码注释就好。我们理一下大致的一个思路。
既然是要设置圆角和背景,那我们首先需要考虑的是在哪里设置,直接设置什么属性肯定是不行的,要不然那我就是疯了写这个。😺我们都应该知道UICollectionView我们要想自定义一些东西或者布局几乎都是通过Layout下手的,那我们要给它设置组背景色和组圆角是不是也在这里进行呢?我们大致的思路是这样的:
给UICollectionView 每一组添加一个修饰View,然后在这个修饰View上我们设置组圆角和背景色,最后我们把CollectionCell 设置成 Clean背景就可以达到我们想要的效果。
理解上面这句话我们第一步就是每组先添加修饰View了!怎么处理呢?
1 2 3 4 | func registDecorationView () { self . register ( PPCollectionReusableView . self , forDecorationViewOfKind : PPCollectionViewDecorationView ) } |
好了这里只是开个头,重点都是下面呢!
NOTE: PPReusableView.self 这个语法在OC中就等于[PPReusableView Class]
PPReusableView是继承与UICollectionReusableView这个装饰View,我们后面会说这个View 后面的 PPCollectionViewSectionBackground 就是我们平时像注册cell时候的一个 identify 而已。
重点
在我们写瀑布流或者别的一些布局的时候,我们都是在哪里重写的? 没错就是 prepare 方法, 我们重点也是在这里进行的,下面代码注释写的很仔细的,要是有不理解的地方可以留言或者Q我,具体的肯定是我们继承 UICollectionViewFlowLayout 写了(要是你也是流式布局的话,要不是你再找UICollectionViewFlowLayout的父亲去继承开发),这里需要注意UICollectionViewFlowLayout 和 UICollectionViewDelegateFlowLayout,别搞混淆了(相信大家不会混淆)。按照如下定义一个PPBaseFlowLayout继承与UICollectionViewFlowLayout,在里面我们重写prepare这个方法。下面的代码是我们给 PPCollectionViewFlowLayout 添加 Extension 处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | // MARK: - set property extension PPCollectionViewFlowLayout { /// 给collectionView设置背景和圆角 func setSectionBackgaoundColorAndCorner (){ /// 获取collectionView的代理 guard let delegate = self . collectionView ?. delegate else { return } /// 没遵守这个协议就不再往下设置 if delegate . conforms ( to : PPCollectionViewDelegateFlowLayout . self ) == false { return } /// collectionView有多少组 let numberOfSections = self . collectionView ?. numberOfSections ?? 0 if numberOfSections == 0 { return } /// 循环遍历各组 设置添加的属性 for section in 0 .. < numberOfSections { /// 一组cell的Item let numberOfItems = self . collectionView ?. numberOfItems ( inSection : section ) ?? 0 if ( numberOfItems < = 0 ) { continue ; } /// 每一组第一个item的Attributes let firstItem = self . layoutAttributesForItem ( at : IndexPath . init ( item : 0 , section : section )) /// 每一组最后一个item的Attributes let lastItem = self . layoutAttributesForItem ( at : IndexPath . init ( item : numberOfItems - 1 , section : section )) /// 满足条件 结束本次循环执行下一次 if (( firstItem == nil ) || ( lastItem == nil )) { continue } /// 实现了insetForSectionAt if delegate . responds ( to : # selector ( UICollectionViewDelegateFlowLayout . collectionView ( _ : layout : insetForSectionAt :))) { let inset = ( delegate as ? UICollectionViewDelegateFlowLayout )? . collectionView ?( self . collectionView !, layout : self , insetForSectionAt : section ) self . sectionInset = inset ! } /// 获取第一个和最后一个item的联合frame ,得到的就是这一组的frame var sectionFrame : CGRect = firstItem !. frame . union ( lastItem !. frame ) /// 设置它的x.y 注意理解这里的x点和y点的坐标,不要硬搬,下面这样写的时候是把inset的left的 /// 距离包含在sectionFrame 开始x的位置 下面的y同逻辑 sectionFrame . origin . x -= self . sectionInset . left - self . marginValue sectionFrame . origin . y -= self . sectionInset . top ///横向滚动 if self . scrollDirection == . horizontal { /// 计算组的宽的时候要把缩进进去的距离加回来 因为缩进是内容缩进 sectionFrame . size . width += self . sectionInset . left + self . sectionInset . right /// 横向滚动的时候 组的高就是collectionView的高 sectionFrame . size . height = self . collectionView !. frame . size . height /// 纵向滚动 } else { /// 纵向滚动的时候组的宽度 这里的道理和上面的x,y的一样,需要你按照自己项目的实际需求去处理 sectionFrame . size . width = self . collectionView !. frame . size . width - ( 2 * self . marginValue ) sectionFrame . size . height += self . sectionInset . top + self . sectionInset . bottom } /// 根据自定义的PPCollectionViewSectionBackground 装饰View初始化一个自定义的PPCollectionLayoutAttributes let attribute = PPCollectionLayoutAttributes . init ( forDecorationViewOfKind : PPCollectionViewDecorationView , with : IndexPath . init ( item : 0 , section : section )) attribute . frame = sectionFrame attribute . zIndex = - 1 /// 实现了backgroundColorForSection if delegate . responds ( to : # selector ( PPCollectionViewDelegateFlowLayout . backgroundColorForSection ( collectionView : layout : section :))){ /// 背景色 attribute . backgroundColor = ( delegate as ? PPCollectionViewDelegateFlowLayout )?. backgroundColorForSection !( collectionView : self . collectionView !, layout : self , section : section ) } /// 实现了cornerForSection if delegate . responds ( to : # selector ( PPCollectionViewDelegateFlowLayout . cornerForSection ( collectionView : layout : section :))) { /// 圆角 attribute . corners = ( delegate as ? PPCollectionViewDelegateFlowLayout )?. cornerForSection !( collectionView : self . collectionView !, layout : self , section : section ) /// 要是是默认的大小就不在实现cornerRadiiForSection attribute . sectionCornerRadii = kDefaultCornerRadii ; } /// 要是自定义了圆角大小 if delegate . responds ( to : # selector ( PPCollectionViewDelegateFlowLayout . cornerRadiiForSection ( collectionView : layout : section :))) { attribute . sectionCornerRadii = ( delegate as ? PPCollectionViewDelegateFlowLayout )?. cornerRadiiForSection !( collectionView : self . collectionView !, layout : self , section : section ) } self . layoutAttributes ?. append ( attribute ) } } } |
NOTE:仔细看代码可以看到圆角和背景色的属性都是设置给PPLayoutAttributes,这玩意又是什么呢?就是我们CollectionView的属性管理者UICollectionViewLayoutAttributes,你进UICollectionViewLayoutAttributes可以看到它的属性有那些,不要忘记我们是根据修饰View初始化得到这个属性的,按照正常的操作我们会在最后返回一个属性数组,自定义过collection布局的应该清楚一些,具体的PPCollectionViewDelegateFlowLayout就是我们继承与UICollectionViewDelegateFlowLayout写的代理了,这个代理里面也就两个方法,圆角和颜色的设置,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | @objc protocol PPCollectionViewDelegateFlowLayout : UICollectionViewDelegateFlowLayout { /// CollectionView 的组设置背景颜色 /// - Parameters: /// - collectionView: collectionView description /// - layout: layout description /// - section: section description /// - Returns: return 组的颜色 @objc optional func backgroundColorForSection ( collectionView : UICollectionView , layout : UICollectionViewLayout , section : NSInteger ) - > UIColor /// CollectionView 的组设置圆角 /// - Parameters: /// - collectionView: collectionView description /// - layout: layout description /// - section: section description /// - Returns: UIRectCorner eg:[.topLeft,.topRight] @objc optional func cornerForSection ( collectionView : UICollectionView , layout : UICollectionViewLayout , section : NSInteger ) - > UIRectCorner /// CollectionView 的组设置圆角的大小 要是默认的12可不实现此方法返回 /// - Parameters: /// - collectionView: collectionView description /// - layout: layout description /// - section: section description /// - Returns: CGSize 圆角大小 @objc optional func cornerRadiiForSection ( collectionView : UICollectionView , layout : UICollectionViewLayout , section : NSInteger ) - > CGSize } |
PPLayoutAttributes 其本质就是一个存储属性的 Model
下面就是它的全部代码
1 2 3 4 5 6 7 8 9 10 | // MARK: - 添加自定义属性 class PPCollectionLayoutAttributes : UICollectionViewLayoutAttributes { /// 添加组背景 var backgroundColor : UIColor ? /// 添加组圆角 var corners : UIRectCorner ? /// 添加组圆角的大小 var sectionCornerRadii : CGSize ? } |
不能忘记了PPReusableView,它的代码也比较的简单,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import Foundation import UIKit // MARK: - 可重复使用视图 class PPReusableView : UICollectionReusableView { override func apply ( _ layoutAttributes : UICollectionViewLayoutAttributes ) { super . apply ( layoutAttributes ) if layoutAttributes . isKind ( of : PPLayoutAttributes . self ) { let layoutAttribute = layoutAttributes as ? PPLayoutAttributes if layoutAttribute !. backgroundColor != nil { self . backgroundColor = layoutAttribute !. backgroundColor } /// 默认设置为 12 以后有需要可以自定义 if layoutAttribute !. corners != nil { self . setRoundingCorners ( layoutAttribute !. corners !, cornerRadii : kDefaultCornerRadii ) } } } } |
返回你的自定义
随后就是返回你前面设置了那么多的属性,具体的就是下面的代码所示了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // MARK: - override extension PPCollectionViewFlowLayout { // NOTE: 该方法会在你每次刷新collection data的时候都会调用 override func prepare () { super . prepare () /// 避免属性重复添加数据过大 self . layoutAttributes ?. removeAll () /// 设置背景和圆角 self . setSectionBackgaoundColorAndCorner () } /// 返回rect中的所有的元素的布局属性 /// - Parameter rect: rect description override func layoutAttributesForElements ( in rect : CGRect ) - > [ UICollectionViewLayoutAttributes ]? { var attributes = super . layoutAttributesForElements ( in : rect ) for attribute in self . layoutAttributes ! { ///判断两个区域是否有交集 if rect . intersects ( attribute . frame ){ attributes ?. append ( attribute ) } } return attributes } /// 给Decorationview返回属性数组 /// - Parameters: /// - elementKind: elementKind description /// - indexPath: indexPath description override func layoutAttributesForDecorationView ( ofKind elementKind : String , at indexPath : IndexPath ) - > UICollectionViewLayoutAttributes ? { if elementKind == PPCollectionViewDecorationView { return self . layoutAttributes ![ indexPath . section ] } return super . layoutAttributesForDecorationView ( ofKind : elementKind , at : indexPath ) } } |
下面就是我们的 -- PPCollectionViewFlowLayout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class PPCollectionViewFlowLayout : UICollectionViewFlowLayout { /// 存储添加的属性 private var layoutAttributes : Array < UICollectionViewLayoutAttributes > ? /// CollectionView的边距 这个值可以自定义 默认是10 public var marginValue : CGFloat = 10 override init () { super . init () self . layoutAttributes = [] /// 注册一个修饰View self . registDecorationView () } func registDecorationView () { self . register ( PPCollectionReusableView . self , forDecorationViewOfKind : PPCollectionViewDecorationView ) } required init ?( coder aDecoder : NSCoder ) { fatalError ( "init(coder:) has not been implemented" ) } } |
最后:
最后我们在最前面说的registClass这个方法我们在PPBaseFlowLayout的初始化方法里面调用就可以了,还有属性数组这写就不用说了吧还是在前面自己定义初始化了。
然后上面代码里面的一些宏定义比如identify还有圆角大小等等这些就根据自己的需求去写吧。
最后在初始化CollectionView的时候layout就是我们定义的PPBaseFlowLayout了,遵守的代理就是PPCollectionViewDelegateFlowLayout,这个需要留意下就OK。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话