[iOS] 정사각형 CollectionView Cell 만들기

Logan·2021년 2월 24일
1

  1. CollectionView > Estimate Size를 None으로 바꿔줍니다.
  2. 여백을 주고 싶다면 Min Spacing의 For Cells와 For Lines를 동일한 값으로 맞춰줍니다.
  3. UICollectionViewDelegateFlowLayout Method로 코드 구현
extension IconChangeViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   	 // Type Casting
        guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return CGSize() }
        let numberOfCells: CGFloat = 4
        let width = collectionView.frame.size.width - (flowLayout.minimumInteritemSpacing * (numberOfCells-1))
        return CGSize(width: width/(numberOfCells), height: width/(numberOfCells))
    }
}

Cell의 사이즈를 관리하는 Delegate는 UICollectionViewDelegateFlowLayout collectionView(_:layout:sizeForItemAt:) 메소드에서 구현할 수 있습니다.
한 줄에 표시하고 싶은 Cell의 갯수를 상수에 저장한 다음 (numberOfCells) Min Spacing을 추가했다면 해당 값을 계산해서 빼줘야합니다.

상수로 값을 입력하는 것보단 해당 속성값으로 계산해주는 게 좋습니다.
Min Spacing 속성은 collectionView(_:layout:sizeForItemAt:) Method의 collectionViewLayout 파라미터에 들어 있으며, UICollectionViewFlowLayout로 다운캐스팅을 해줘야 해당 속성에 접근할 수 있습니다.

profile
iOS개발자 꿈나무

0개의 댓글