Swift

[iOS|Swift] UICollectionView Cell 크기 지정하기

moving 2022. 4. 16. 18:16
728x90

 

UICollectionView란?

데이터 아이템의 정렬된 컬렉션을 관리하고 사용자 지정 가능한 레이아웃을 사용하여 표시하는 개체입니다.

https://developer.apple.com/documentation/uikit/uicollectionview

 

UICollectionView Cell 이란?

 

 

 사진에서 보이는 것과 같이 초록색 사각형 하나를 Cell 이라고 합니다.

 Cell은 컬렉션뷰의 주요 콘텐츠를 표시합니다. 

 컬렉션뷰는 컬렉션뷰 데이터 소스 객체에서 표시할 셀에 대한 정보를 가져옵니다.

 

 

  다음 사진과 같이 동일한 크기를 가진 컬렉션뷰를 만들어보려고 합니다.

 

 

 

 

 

 

 

 

1. 스토리보드에서 Collection View Controller 를 만들어 줍니다.

2. Cocoa Touch Class인 새로운 파일을 만들어 줍니다.

Subclass of는 각각 UICollectionViewControllerUICollectionViewCell 인 파일을 만들어 줍니다.

 

3. UICollectionView 스토리보드에서 Class를 지정합니다. 

 

4. UICollectionViewCell 스토리보드에서 Identifier를 지정합니다.

private let reuseIdentifier = "Cell"

 

5. UICollectionViewController에 nib 파일을 등록합니다.

override func viewDidLoad() {
    super.viewDidLoad()

    // Register cell classes
    self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}

 

6. UICollectionViewDataSource 메소드를 구현합니다.

// MARK: - UICollectionViewDataSource

// 섹션의 갯수를 묻는 메서드
override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

// 지정된 섹션에 표시할 셀의 개수를 묻는 메서드
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 21
}

// 컬렉션뷰의 지정된 위치에 표시할 셀을 요청하는 메서드
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

	cell.backgroundColor = .green
    
    return cell
}

 

7. UICollectionViewDelegateFlowLayout 프로토콜을 채택 후 메소드를 구현합니다.

// MARK: - UICollectionViewDelegateFlowLayout

let cellMarginSize: CGFloat = 10.0

// 셀 크기 지정
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.bounds.width
    let numberOfItemsPerRow: CGFloat = 3
    let spacing: CGFloat = self.cellMarginSize
    let availableWidth = width - spacing * (numberOfItemsPerRow + 1)
    let itemDimension = floor(availableWidth / numberOfItemsPerRow)

    return CGSize(width: itemDimension, height: itemDimension)
}

// 섹션에서 콘텐츠를 배치하는 데 사용되는 여백
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}

// 그리드의 항목 줄 사이에 사용할 최소 간격
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return self.cellMarginSize
}

// 같은 행에 있는 항목 사이에 사용할 최소 간격
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return self.cellMarginSize
}