日常開(kāi)發(fā)中最常用的控件莫過(guò)于 UITableView 和 UICollectionView,隨著應(yīng)用越來(lái)越復(fù)雜低零,以前的 UICollectionViewFlowLayout 布局已經(jīng)滿足不了需求婆翔,而自定義布局又過(guò)于復(fù)雜,所以在 iOS 13 中 Apple 為 UICollectionView 推出了組合布局 UICollectionViewCompositionalLayout掏婶,這對(duì)于 UICollectionView 是一個(gè)全新的升級(jí)啃奴,它將賦予 UICollectionView 更多的可能性。
特點(diǎn)
- Composable:可組合雄妥,使用簡(jiǎn)單的組合成復(fù)雜的最蕾。
- Flexible:靈活瘟则,可以用組合布局來(lái)寫(xiě)任何的布局淀弹。
- Fast:運(yùn)行速度快干奢。
概念
UICollectionViewCompositionalLayout 是在已有的 Item 和 Section 的基礎(chǔ)上,增加了一個(gè) Group 的概念。多個(gè) Item 組成一個(gè) Group ,多個(gè) Group 組成一個(gè) Section,層級(jí)關(guān)系變?yōu)椋?code>Item -> Group -> Section -> Layout争剿。
- 粗粒度
- 細(xì)粒度
布局核心
NSCollectionLayoutSize
決定了一個(gè)元素的大小。表達(dá)一個(gè)元素的 Size 有三種方法:
- fractional:表示一個(gè)元素相對(duì)于他的父視圖的比例。(Item 的父視圖是 Group飒筑,Group 的父視圖是 Section) 。
// 占據(jù)Group寬和高各25%
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.25), heightDimension: .fractionalHeight(0.25))
- absolute:表示將元素的寬或者高寫(xiě)成固定一個(gè)值。
let widthDimension = NSCollectionLayoutDimension.absolute(200)
let heightDimension = NSCollectionLayoutDimension.absolute(200)
- estimated:表示預(yù)估高度。一般用于自適應(yīng)大小,會(huì)根據(jù)自動(dòng)布局決定元素的大小。
let widthDimension = NSCollectionLayoutDimension.estimated(200)
let heightDimension = NSCollectionLayoutDimension.estimated(200)
NSCollectionLayoutItem
描述一個(gè) Item 的布局,通過(guò) NSCollectionLayoutSize 決定一個(gè) Item 的大小苏遥,定義如下:
class NSCollectionLayoutItem {
convenience init(layoutSize: NSCollectionLayoutSize)
var contentInsets: NSDirectionalEdgeInsets
}
NSCollectionLayoutGroup
- Group 是新引入的組成布局的基本單元叨吮,它有三種形式
- 水平(horizontal)
- 垂直(vertical)
- 自定義(custom)
- Group 的大小頁(yè)需要通過(guò) NSCollectionLayoutSize 決定涵叮。如果是自定義布局,需要傳入一個(gè) NSCollectionLayoutGroupCustomItemProvider 來(lái)決定這個(gè) Group 中 Item 的布局方式航缀。
- 通過(guò) Group 可以在同一個(gè) Section 中實(shí)現(xiàn)不同的布局方式。定義如下:
class NSCollectionLayoutGroup: NSCollectionLayoutItem {
class func horizontal(layoutSize: NSCollectionLayoutSize, subitems: [NSCollectionLayoutItem]) -> Self
class func vertical(layoutSize: NSCollectionLayoutSize, subitems: [NSCollectionLayoutItem]) -> Self
class func custom(layoutSize: NSCollectionLayoutSize, itemProvider: NSCollectionLayoutGroupCustomItemProvider) -> Self
}
NSCollectionLayoutSection
和之前 UICollectionView 的 Section 的定義類似,定義如下:
class NSCollectionLayoutSection {
convenience init(layoutGroup: NSCollectionLayoutGroup)
var contentInsets: NSDirectionalEdgeInsets
}
基本使用
使用步驟
- 創(chuàng)建 Item 的 NSCollectionLayoutSize购岗,然后創(chuàng)建 NSCollectionLayoutItem乾吻。
- 創(chuàng)建 Group 的 NSCollectionLayoutSize鸭你,然后根據(jù) Item 創(chuàng)建 NSCollectionLayoutGroup。
- 根據(jù) Group 創(chuàng)建 NSCollectionLayoutSection剖效。
- 根據(jù) Section 創(chuàng)建 UICollectionViewCompositionalLayout嫉入。
案例一
func generateLayout() -> UICollectionViewCompositionalLayout {
//1 構(gòu)造Item的NSCollectionLayoutSize
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.25),
heightDimension: .fractionalHeight(1.0))
// 2 構(gòu)造NSCollectionLayoutItem
let item = NSCollectionLayoutItem(layoutSize: itemSize)
// 3 構(gòu)造Group的NSCollectionLayoutSize
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalWidth(0.1))
// 4 構(gòu)造NSCollectionLayoutGroup
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: groupSize,
subitems: [item])
// 5 構(gòu)造NSCollectionLayoutSection
let section = NSCollectionLayoutSection(group: group)
// 6 構(gòu)造UICollectionViewCompositionalLayout
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
案例二
func generateLayout() -> UICollectionViewCompositionalLayout {
// 頂部Item
let topItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(9/16))
let topItem = NSCollectionLayoutItem(layoutSize: topItemSize)
topItem.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
// 底部Item
let bottomItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1.0))
let bottomItem = NSCollectionLayoutItem(layoutSize: bottomItemSize)
bottomItem.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
// 底部Group
let bottomGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(0.5))
let bottomGroup = NSCollectionLayoutGroup.horizontal(layoutSize: bottomGroupSize, subitem: bottomItem, count: 2)
// 組合兩個(gè)Group
let fullGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(9/16 + 0.5))
let nestedGroup = NSCollectionLayoutGroup.vertical(layoutSize: fullGroupSize, subitems: [topItem, bottomGroup])
// Section
let section = NSCollectionLayoutSection(group: nestedGroup)
// Layout
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
間距
間距主要分 3 種:Item 與 Item 之間澎粟,Group 與 Group 之間,Section 與 Section 之間,主要有兩種設(shè)置方式:
contentInsets
Item稚晚、Group 和 Section 都有一個(gè)屬性 contentInsets 用于設(shè)置邊距。
Item的contentInsets
- 設(shè)置語(yǔ)法
item.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
- 當(dāng)給 Item 設(shè)置
contentInsets
后的示意圖:
灰色區(qū)域是 Item摸柄,紅色框是 Item 的邊界颤练,紅色的上下左右邊距就是設(shè)置的 contentInsets。
Group的contentInsets
- 設(shè)置語(yǔ)法
group.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
- 當(dāng)給 Group 設(shè)置
contentInsets
后的示意圖:
灰色區(qū)域是 Item驱负,紅色框是 Item 的邊界嗦玖,藍(lán)色框是 Group 的邊界患雇,藍(lán)色的上下左右邊距就是設(shè)置的 contentInsets。
Section的contentInsets
- 設(shè)置語(yǔ)法
section.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
- 當(dāng)給 Section 設(shè)置
contentInsets
后的示意圖:
灰色區(qū)域是 Item宇挫,紅色框是 Item 的邊界苛吱,藍(lán)色框是 Group 的邊界,綠色框是 Section 的邊界器瘪,綠色的上下左右邊距就是設(shè)置的 contentInsets翠储。
為了使整體的上下左右邊距一樣,通常需要同時(shí)設(shè)置 Item 和 Group 的
contentInsets
娱局。
Spacing
可以直接給 Group 和 Section 設(shè)置相應(yīng)的 Spacing 以達(dá)到設(shè)置 Item 和 Group 之間間距的目的彰亥,但這種需要精確計(jì)算間距的值咧七,因?yàn)殚g距會(huì)擠占 Item 和 Group 的空間衰齐。
// Item Spacing
group.interItemSpacing = .fixed(8) // 也可以使用.flexible(<spacing>)來(lái)決定 Item 之間的最佳間距
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .fixed(8), top: .fixed(8), trailing: .fixed(8), bottom: .fixed(8))
// Group Spacing
section.interGroupSpacing = 8
NSCollectionLayoutBoundarySupplementaryItem
附加視圖,一般用于設(shè)置頭部和尾部继阻。
let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44))
let header = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize, elementKind: "header", alignment: .top)
let footerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44))
let footer = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: footerSize, elementKind: "footer", alignment: .bottom)
// pinToVisibleBounds決定是否懸停
header.pinToVisibleBounds = true
section.boundarySupplementaryItems = [header, footer]
使用之前需要注冊(cè)耻涛,下面會(huì)講解。
NSCollectionLayoutAnchor
在 Item 中瘟檩,可能需要給他加上小紅點(diǎn)或者未讀消息數(shù)抹缕,在 UICollectionViewCompositionalLayout 中,可以通過(guò) NSCollectionLayoutSupplementaryItem 和 NSCollectionLayoutAnchor 這兩個(gè)類來(lái)去定義一個(gè)這樣的視圖墨辛。
- 實(shí)現(xiàn)一個(gè)UICollectionReusableView
class BadgeView: UICollectionReusableView {
static let reuseIdentifier = "badge"
let imageView = UIImageView(image: UIImage(systemName: "heart.fill"))
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
}
- 注冊(cè)SupplementaryView
collectionView.register(
BadgeView.self,
forSupplementaryViewOfKind: "badge",
withReuseIdentifier: BadgeView.reuseIdentifier)
- 設(shè)置SupplementaryView
dataSource.supplementaryViewProvider = {
(collectionView: UICollectionView, kind: String, indexPath: IndexPath)
-> UICollectionReusableView? in
if let badgeView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: BadgeView.reuseIdentifier,
for: indexPath) as? BadgeView {
return badgeView
} else {
fatalError("Cannot create Supplementary")
}
}
- 設(shè)置Badge
let badgeAnchor = NSCollectionLayoutAnchor(edges: [.top, .trailing],
fractionalOffset: CGPoint(x: 0.5, y: -0.5))
let badgeSize = NSCollectionLayoutSize(widthDimension: .absolute(16),
heightDimension: .absolute(16))
let badge = NSCollectionLayoutSupplementaryItem(layoutSize: badgeSize, elementKind: "badge", containerAnchor: badgeAnchor)
let item = NSCollectionLayoutItem(layoutSize: itemSize, supplementaryItems: [badge])
- 效果
滾動(dòng)Section
通過(guò)設(shè)置 Section 的 orthogonalScrollingBehavior 參數(shù)卓研,可以實(shí)現(xiàn) Section 的不同的滾動(dòng)方式。
- 滾動(dòng)類型
public enum UICollectionLayoutSectionOrthogonalScrollingBehavior : Int {
// 默認(rèn)行為睹簇,根據(jù)configuration.scrollDirection設(shè)置的主軸布局
case none = 0
case continuous = 1
case continuousGroupLeadingBoundary = 2
case paging = 3
case groupPaging = 4
case groupPagingCentered = 5
}
- 設(shè)置滾動(dòng)
section.orthogonalScrollingBehavior = .continuous
總結(jié)
UICollectionViewCompositionalLayout 徹底顛覆了 UICollectionView 的布局體驗(yàn)奏赘,大大拓展了 UICollectionView 的可塑性,甚至從某種程度上來(lái)說(shuō)太惠,UI 開(kāi)發(fā)中的復(fù)雜布局已經(jīng)非它莫屬磨淌。