Swift

Swift - UICollectionViewFlowLayout 셀 크기 다르게 구현 (UILabel)

Goniii 2024. 12. 2. 22:52

문제 상황


 

  • 셀의 heigh은 고정이지만, width는 글자의 길이에 따라 다름
  • 기존의 UICollectionView 선언 과정에서 layout의 itemSize를 지정하는 방법은 모든 셀의 사이즈가 고정되기 때문에 사용할 수 없음

 

해결 과정


  • String을 Extension하여 UILabel의 text, font에 따라 UILabel의 너비를 구하는 함수 구현
// String을 Extension하여 UILabel의 text, font에 따라 UILabel의 너비를 구하는 함수 구현
extension String {
    func getUILabelWidth(fontSize : CGFloat, fontWeight : UIFont.Weight) -> CGFloat {
        let label = UILabel()
        label.text = self
        label.font = .systemFont(ofSize: fontSize, weight: fontWeight)
        label.sizeToFit()
        return label.frame.width // 너비 반환
    }
}

 

  • UICollectionViewDelegate를 이용하여 collectionView(_:layout:sizeForItemAt:) 사용
    • 각각의 셀 사이즈를 반환해주면 됨
    extension SearchViewController : UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let width = items[indexPath.row].title.getLabelWidth(fontSize: 13, fontWeight: .regular)
            let padding : CGFloat = 20 // 라벨 좌우 여백 추가 (UILabel의 alignment는 center)
            return CGSize(width: width + padding, height: 32)
        }
    }
    // 위 items = RecommendSearchModel.dummy()
    
    extension RecommendSearchModel {
        static func dummy() -> [RecommendSearchModel] {
            [
                RecommendSearchModel(title: "채원 슈프림 후리스"),
                RecommendSearchModel(title: "나이키V2K런"),
                RecommendSearchModel(title: "뉴발란드996"),
                RecommendSearchModel(title: "신상 나이키 콜라보"),
                RecommendSearchModel(title: "허그 FW 패딩"),
                RecommendSearchModel(title: "벨루어 눕시"),
            ]
        }
    }

→ item의 title과 font를 이용하여 UILabe의 너비를 구하고 UILabel의 text를 center로 정렬 후 padding으로 좌우 여백 추가

 

 

 

결과 화면

 

참고 자료