seong_hye, the developer

UIKit) UICollectionvView - layout vs flowlayout 본문

IOS/UIKit

UIKit) UICollectionvView - layout vs flowlayout

seong_hye 2022. 11. 6.

UICollectionView 속에는 UICollectionViewLayout과 UICollectionViewFlowLayout이 있어

사용할 때 헷갈려서 한번 이 둘의 차이에 대해 한 번 정리해보려고 한다.


📘 UICollectionViewLayout - 추상 클래스 (설계도)

모든 레이아웃의 기반이 되는 추상 클래스

직접 사용하는 경우는 드물고, 서브클래싱해서 커스텀 레이아웃을 만들 때 사용함

이 클래스를 상속해서 자신만의 layout behavior를 정의할 수 있음

 

🔍  주요 역할

- 셀의 위치 및 크기 계산 (layoutAttributesForElements)

- 콘텐츠 사이즈 제공 (collectionViewContentSize)

- 레이아웃 무효화 처리 (shouldInvalidateLayout ...)

 

🔍 사용 예제

// 1.레이아웃 설정
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumLineSpacing = 16
layout.sectionInset = UIEdgeInsets(top: 20, left: 16, bottom: 20, right: 16)

//2. 컬렉션 뷰 초기화
colectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)

 

🔍 주요 함수 (메서드)

prepare()

레이아웃 계산을 시작하기 전에 호출

셀의 위치/ 크기 계산을 여기서 계산함

override func prepare() {
	super.prepare()
    // 셀 위치 계산, 속성 설정 등
}

 

layoutAttributesForElements(in:)

지정된 영역 안에 있는 모든 셀, 헤더, 푸터의 레이아웃 속성을 반환함

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
	return super.layoutAttributesForElements(in: rect)
}

 

layoutAttributesForItem(at:)

특정 셀에 대한 레이아웃 속성을 반환함

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
	return super.layoutAttributesForItem(at: indexPath)
}

 

collectionViewContentSize

전체 콘텐츠 영역의 사이즈를 반환함

스크롤 가능한 크기를 결정

override var collectionViewContentSize: CGSize {
	return CGSize(width: 1000, height: 1000)
}

 

🔍 예시 화면

 


📘 UICollectionVieFlowLayout - 추상 클래스 (설계도)

UICollectionViewLayout을 상속한 애플이 기본 제공하는 구현 클래스

행 또는 열 방향으로 흐르는 레이아웃을 제공함

보통 많이 사용하는 형태 (그리드, 리스트)를 구현

 

🔍  주요 역할

- 스크롤 방향 설정 (수직/수평)

- 셀 간 간격 (minimumLineSpacing, minimumInteritemSpacing)

- 섹션 인셋 (sectionInset)

- 셀 사이즈 (itemSize, estimatedItemSize)

 

🔍 사용 예제

// 1.레이아웃 설정
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumLineSpacing = 16
layout.sectionInset = UIEdgeInsets(top: 20, left: 16, bottom: 20, right: 16)

//2. 컬렉션 뷰 초기화
colectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)

 

🔍 주요 프로퍼티 (Property)

프로퍼티 설명
scrollDirection .vertical 또는 .horizontal로 스크롤 방향 지정
itemSize 셀 하나의 크기 지정 (CGSize)
estimatedItemSize 자동 크기 설정 셀을 위한 추정 크기 (AutoLayout 셀 사용 시)
minimumLineSpacing 행(줄) 간 간격
minimumInteritemSpacing 열(칸) 간 간격
sectionInset 각 섹션의 간격 (UIEdgeInsets)
headerReferenceSize 헤더 뷰의 크기
footerReferenceSize 푸터 뷰의 크기
sectionHeadersPinToVisibleBounds 헤더를 화면 상단에 고정할지 여부 (true/false)
sectionFootersPinToVisibleBounds 푸터를 화면 하단에 고정할지 여부

 

🔍 주요 함수 (메서드)

prepare()

레이아웃 계산을 시작하기 전에 호출

itemSize나 커스텀 위치를 직접 계산하려면 이 함수에서 작업함

override func prepare() {
	super.prepare()
    // 셀 위치 계산, 속성 설정 등
}

 

layoutAttributesForElements(in:)

지정된 영역 안에 있는 모든 셀, 헤더, 푸터의 레이아웃 속성을 반환함

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
	return super.layoutAttributesForElements(in: rect)
}

 

layoutAttributesForItem(at:)

특정 셀에 대한 레이아웃 속성을 반환함

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
	return super.layoutAttributesForItem(at: indexPath)
}

 

collectionViewContentSize

전체 콘텐츠의 사이지를 반환함

스크롤 범위에 영향을 줌

override var collectionViewContentSize: CGSize {
	return super.collectionViewContentSize
}

 

shouldInvalidateLayout(forBoundsChange:)

뷰 크기 변경(ex.회전) 시 레이아웃을 다시 계산할 지 여부를 반환함

override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
	return true // 크기 변화에 따라 다시 레이아웃 계산
}

 

🔍 예시 화면


🔹정리

항목 UICollectionViewLayout UICollectionViewFlowLayout
클래스 유형 추상 클래스 (기반 클래스) 구현 클래스 (기본 flow 제공)
사용 목적 직접 상속해서 커스텀 레이아웃 구현 기본 flow 형태 (가로/세로 리스트, 그리드 등)
유연성 매우 높음 (자유롭게 커스터마이즈 가능) 제한적 (Flow 형식만 가능)
난이도 복잡함 간단함
사용 경우 특별한 배치 (원형, 겹침, 자유 위치 등) 일반적인 리스트, 그리드

 

Comments