環境
Xcode 13.1
Swift 5.5.1
CollectionViewをつくる
View Controller > View の上に、Collection Viewを配置
Section Header
をSB上で表示するには Attributes Inspector
> Accessories
> Section Header
にチェックしました
背景色の設定はStoryboard上で行いました
HeaderやCellのidentifierを設定
HeaderやCellのクラスを作成する
- CollectionViewにはTableViewとは異なり、中はほとんど空なので自分で作る
- Headerのクラスは
UICollectionReusableView
import UIKit
class CollectionReusableView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
}
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
Header / CellのCustom Classを設定
コードの実装
-
TableView
でrowとする部分はrow
でもエラーは発生しないものの基本的にitem
を使います -
CollectionView
では基本レイアウトのようなものが存在しないので、全て設定しないと思ったようなものになりません(ここではUICollectionViewFlowLayout
を使用)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
// CellのUILabelに表示するテキスト
var data = [["0A", "0B", "0C", "0D", "0E"], ["1A", "1B"], ["2A", "2B", "2C"]]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
// レイアウト設定(任意)
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15)
let cellSize = view.bounds.width / 3 - 20
layout.itemSize = CGSize(width: cellSize, height: cellSize)
layout.headerReferenceSize = CGSize(width: view.bounds.width, height: 50)
collectionView.collectionViewLayout = layout
}
}
extension ViewController: UICollectionViewDataSource {
// Sectionの数
func numberOfSections(in collectionView: UICollectionView) -> Int {
data.count
}
// 各Sectionのアイテム(Cell)数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data[section].count
}
// Headerに表示するビューの設定
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! CollectionReusableView
header.label.text = "Section\(indexPath.section)"
return header
}
// アイテム(Cell)に表示するビューの設定
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.label.text = data[indexPath.section][indexPath.item]
cell.backgroundColor = .green![Something went wrong]()
return cell
}
}
誤りなどがありましたら、ご指摘いただければ幸いです。