문제 상황
- 셀의 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으로 좌우 여백 추가
결과 화면
참고 자료
- https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview
- https://boidevelop.tistory.com/87
'Swift' 카테고리의 다른 글
Swift - ARC (Automatic Reference Count) 정리 및 강한 순환 참조 해결 (0) | 2024.12.08 |
---|---|
Swift - Struct와 Class 선택과 차이점 (0) | 2024.12.06 |
Swift - KeyChain이란? (0) | 2024.11.24 |
Swift - modal 여러 개 한 번에 dismiss 하기 (0) | 2024.11.20 |
Swift - 카카오 로그인 사용자 정보 가져오기 (1) | 2024.11.20 |