Xcode Study
CollectionView
JasonYang
2023. 12. 14. 09:44
//
// ViewController.swift
// UICollectionView
//
// Created by Jason Yang on 12/14/23.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let data = ["Item 1", "Item 2", "Item 3"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.frame = view.bounds
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = .white
view.addSubview(collectionView)
}
// UICollectionViewDataSource
/* [필수] 행 수를 보고합니다. */
// section: 컬렉션뷰의 section을 나타내는 식별자 입니다. 이를 바탕으로 해당 섹션의 count를 반환합니다.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
/* [필수] 각 행에 대한 셀을 제공합니다. */
// indexPath: 컬렉션뷰에서 Row(행)을 찾는 경로입니다. 이를 바탕으로 적절한 cell을 반환합니다.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = .blue
return cell
}
// UICollectionViewDelegate
/* 행이 선택되었을 때 호출 */
// indexPath: 컬렉션뷰에서 선택된 Row(행)을 찾는 경로입니다. 이를 바탕으로 어떤 행이 선택되었는지 파악할 수 있습니다.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Selected: \(data[indexPath.row])")
collectionView.deselectItem(at: indexPath, animated: true)
}
// UICollectionViewDelegateFlowLayout
/* 셀의 크기를 보고합니다 */
// collectionViewLayout: 컬렉션뷰에서 사용된 레이아웃입니다. 행의 크기를 반환할 때 참고할 수 있습니다.
// indexPath: 컬렉션뷰에서 선택된 Row(행)을 찾는 경로입니다. 이를 바탕으로 어떤 행의 크기를 반환할지 판단할 수 있습니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}