1️⃣ 문제 상황

셀의 너비를 라벨의 길이에 맞추어 조절해주고 싶은 상황

셀의 너비를 라벨의 길이에 맞추어 조절해주고 싶은 상황

2️⃣ 검색

검색을 해보기로 함

(검색어) dynamic width cell swift

Dynamic cell width of UICollectionView depending on label width

3️⃣ 적용 코드

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: categoryTitles[indexPath.item].size(withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14)]).width + 20, height: 32)
}

4️⃣ 코드 분석

기본 배경

CGSize란

CGSize 는 크기 값(너비와 높이 값)을 포함하는 구조체입니다.