[swift] 그리드 레이아웃 구성하기
Swift로 그리드 레이아웃을 구성하는 것은 간단하지만, 약간의 코드 작업이 필요합니다.
import UIKit
class GridViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let numberOfItemsPerRow: CGFloat = 3
let spacing: CGFloat = 8
// 그리드 레이아웃 설정
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let totalSpacing = (2 * spacing) + ((numberOfItemsPerRow - 1) * spacing)
let width = (collectionView.bounds.width - totalSpacing) / numberOfItemsPerRow
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return spacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return spacing
}
}
위의 예시 코드에서는 UICollectionViewController
를 상속받은 GridViewController
클래스를 선언하고, UICollectionViewDelegateFlowLayout
프로토콜을 준수합니다.
sizeForItemAt
함수를 사용하여 각 항목의 크기를 정의하고, minimumLineSpacingForSectionAt
과 minimumInteritemSpacingForSectionAt
함수를 사용하여 간격을 정의합니다.
더 많은 기능을 추가하여 진보된 그리드 레이아웃을 구성할 수 있으며, 이는 개발자의 창의성에 따라 다르게 구성될 수 있습니다.
참조:
- https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/implementing_modern_collection_views
- https://www.raywenderlich.com/5436806-uicollectionview-custom-layout-tutorial-building-a-spinning-grid