UICollectionView
— это мощный UIKit-компонент для отображения упорядоченных коллекций данных с гибкой системой компоновки. Представляет собой эволюцию UITableView
с расширенными возможностями.
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.addSubview(collectionView)
UICollectionViewFlowLayout
)collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
collectionView.register(
SectionHeader.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "Header"
)
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell",
for: indexPath) as! PhotoCell
cell.configure(with: photos[indexPath.item])
return cell
}
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
let photo = photos[indexPath.item]
showDetail(for: photo)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (collectionView.bounds.width - 30) / 2
return CGSize(width: width, height: width * 1.5)
}
UICollectionViewFlowLayout
(линейная/сеточная)UICollectionViewLayout
class CustomLayout: UICollectionViewLayout {
// Реализация методов layout
override func prepare() {
// Вычисления атрибутов
}
}
var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) {
collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(...)
cell.configure(with: item)
return cell
}
let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
let itemSize = NSCollectionLayoutSize(...)
// Конфигурация сложной layout-структуры
}
Правила эффективных коллекций:
Проблемные места:
UICollectionViewCell
class PhotoCell: UICollectionViewCell {
override var isHighlighted: Bool {
didSet { animateSelection() }
}
}
UICollectionView
— это универсальный инструмент для создания сложных адаптивных интерфейсов с практически неограниченными возможностями кастомизации. Для базовых сеток достаточно UICollectionViewFlowLayout
, для сложных сценариев — Compositional Layout
и Diffable Data Source
. Ключевое преимущество перед UITableView
— произвольная организация элементов и поддержка нелинейных layout'ов.