■CollectionView とは
タイル型の四角いcellを作り
縦や横に並べてレイアウトを組む物です。
Instagram等で使われている。
多分youtubeも?...
1
storyboardにCollectionViewを置く 画面全体に広げる制約つける。
CollectionViewをViewController.swiftファイルに紐づけコードを書く
コードはほとんどUITableViewと同じ
■UICollectionViewDataSource
でcellの数を決めどのcellか教えてあげる。
■UICollectionViewDelegateFlowLayout
これについては後で説明します。
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var collectionView: UICollectionView!
let cellID = "cellID"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//cellの数を決める。 とりあえず10個
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
10
}
//cellの指定
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
cell.backgroundColor = .red
return cell
}
}
2 cellの大きさを決める。
■UICollectionViewDelegateFlowLayoutを使用する。
その名の通りLayoutに関する関数をもっている。
下記コードを追加
//cellの大きさを決める。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//画面横幅いっぱいのサイズ
let width = self.view.frame.width
//横幅と縦幅を指定して返す。
return .init(width: width, height: width)
}
このように一つのcellのデカさが横いっぱいに広がったため残りのcellが縦に並んでいる。
3 XIBでcellの中身をカスタマイズして作成。
■File -> NEW -> File でViewを指定して作成
これでXibが作られる。
元からある画面を消す
+マークからCollectionViewCellを指定し追加
中身にimageViewだったりlabelを追加し制約をつけカスタマイズする。
右上のidentifierにViewControllerで作った変数のID名を入れる。
4 Cellのファイルを作成
cellのファイルを作成し
xibのファイルとして紐づける。
cellのファイルの中身
import UIKit
class ViewCell: UICollectionViewCell {
@IBOutlet private weak var imageView: UIImageView!
//下記コードでXibの中身をカスタマイズして表示
override func awakeFromNib() {
super.awakeFromNib()
//imageを丸く
imageView.layer.cornerRadius = 20/1
}
}
■viewControllerのViewDidLoadの中身に
collectionView.register(UINib(nibName: "ViewCell", bundle: nil), forCellWithReuseIdentifier: cellID)を追加
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let cellID = "cellID"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
//xibを紐づける。 cellファイルを指定 IDを指定
collectionView.register(UINib(nibName: "ViewCell", bundle: nil), forCellWithReuseIdentifier: cellID)
}
}
5 仕上げ
■Storyboardの
Collection View Flow LayOutを選択
右メニューのEstimate Size を Noneに変更
こうすることによってxibで作成した通りになる。
Collection View Flow LayOutの仕様により
Estimate Sizeが Automaticになっていれば名前の通りにオートでレイアウトが作られてしまう。