完成形はこんな感じです

機能説明
* Sliderを右にスライドさせると、CollectionViewのcellが表示されます。
コードと簡単解説
-
.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
の箇所は、CollectionViewのレイアウトを設定 - UISliderの最小値は0、最大値は100にしています(cellを最大100個表示できる様にしている)
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var cellCountSlider: UISlider!
let collectionViewFlowLayout = UICollectionViewFlowLayout()
var cellCount = 0
override func viewDidLoad() {
super.viewDidLoad()
cellCountSlider.minimumValue = 0
cellCountSlider.maximumValue = 100
collectionView.delegate = self
collectionView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
collectionView.collectionViewLayout = collectionViewFlowLayout
}
@IBAction func cellCountUpMinus(_ sender: UISlider) {
if sender.value >= 0{
cellCount = Int(sender.value)
collectionView.reloadData()
}
}
}
-
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}
では表示するcellの個数を設定します。 -
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}
では表示するcellとそのcellに表示する内容を設定します。 -
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {}
ではcellのwidthやheightの設定をしています
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = .systemTeal
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width / 4 - 10, height: collectionView.frame.size.width / 4)
}
}
終わり
最近、TableViewを使うことが多くて、なかなかCollectionViewを使えてなかったので復習の為に作りました。
ご指摘や質問などありましたら、喜んで受け付けてます。