鍾情圓角怎么辦?
最近由於我們的UI設計鍾情於圓角搞得我很方,各種圓角漸變,於是就有了下面這篇給UICollectionView的組設置圓角和背景色的一個小封裝,拿出來和大家分享一下,里面的具體的一下細節都在代碼注釋里面,大家留意下代碼注釋就好。我們理一下大致的一個思路。
既然是要設置圓角和背景,那我們首先需要考慮的是在哪里設置,直接設置什么屬性肯定是不行的,要不然那我就是瘋了寫這個。😺我們都應該知道UICollectionView我們要想自定義一些東西或者布局幾乎都是通過Layout下手的,那我們要給它設置組背景色和組圓角是不是也在這里進行呢?我們大致的思路是這樣的:
給UICollectionView 每一組添加一個修飾View,然后在這個修飾View上我們設置組圓角和背景色,最后我們把CollectionCell 設置成 Clean背景就可以達到我們想要的效果。
理解上面這句話我們第一步就是每組先添加修飾View了!怎么處理呢?
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 處理。
// 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寫的代理了,這個代理里面也就兩個方法,圓角和顏色的設置,代碼如下:
@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
下面就是它的全部代碼
// MARK: - 添加自定義屬性 class PPCollectionLayoutAttributes: UICollectionViewLayoutAttributes { /// 添加組背景 var backgroundColor:UIColor? /// 添加組圓角 var corners:UIRectCorner? /// 添加組圓角的大小 var sectionCornerRadii:CGSize? }
不能忘記了PPReusableView,它的代碼也比較的簡單,如下
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) } } } }
返回你的自定義
隨后就是返回你前面設置了那么多的屬性,具體的就是下面的代碼所示了
// 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
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。