[iOS] UICollectionViewCell의 동적인 사이즈 적용

z-wook·2023년 8월 30일
0
post-thumbnail

Dynamic Cell Size

아래 사진과 같이 Category의 Label 크기에 따라 Cell Size를 다르게 적용시키고 싶을 때 어떻게 구현해야 할지 아래의 예시 코드를 통해 알아보겠습니다.


예시 코드

func getCategoryCellSize(categoryText: String) -> (CGFloat, CGFloat) {
	let label = UILabel()
	label.font = .systemFont(ofSize: categoryFontSize, weight: categoryFontWeight)
	label.text = categoryText
	label.sizeToFit()
	return (label.frame.width, label.frame.height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
	guard let viewModel = viewModel else { return CGSize() }
	let categoryTitle = Category.allCases[indexPath.row].categoryTitle
	let size = viewModel.getCategoryCellSize(categoryText: categoryTitle)
	let cellInset: CGFloat = 20
	return CGSize(width: size.0 + cellInset, height: size.1 + cellInset)
}
  • getCategoryCellSize
    Label에 text를 설정하고 sizeToFit를 사용하여 텍스트에 맞게 라벨의 크기가 조정시킨 후
    해당 Label의 크기를 반환시키는 함수입니다.
  • collectionView(_:layout:sizeForItemAt:)
    CollectionView의 메서드 중 하나로 Cell Size를 정할 수 있습니다.
    해당 메서드에서 getCategoryCellSiz를 사용하여 Label의 Size를 return 받고, return 받은 Label의 크기만큼 Cell Size를 지정해 주면 동적인 Cell을 만들 수 있습니다.
profile
🍎 iOS Developer

0개의 댓글