apple/Docs, iOS, Swift
[iOS] UICollectionView에 대해서 알아보기 3편 (동적 Cell)
lgvv
2022. 8. 22. 22:20
UICollectionView에 대해서 알아보기 3편
✅ 이번에는 CollectionView를 이용하여 height을 동적으로 구성하는 방법에 대해서 알아보자.
이 부분에 있어서는 여러개의 구글링을 하면서 여러개의 포스팅을 찾아보았다.
- dummyCell 방법이 가장 흔한 것 같은데, 잘 안되었다.
- 그래서 이 방법 사용 고고!
- dummyCell의 경우에는 내 코드를 가져가서 리팩토링해서 알려주면 좋겠다,, 누군가
소스코드
🌿 결과물 🌿
✅ 코드
/// 셀의 레이아웃 정보를 구성
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
print("👉 \(#function)")
let width = UIScreen.main.bounds.width
// MARK: - 동적으로 셀을 구성.
let element = restaurantDetails[indexPath.row].description // 문자열
let fontSize: CGFloat = 22 // 폰트 사이즈
let limit: CGFloat = 25 // 여백을 포함한 기본 height - 폰트 사이즈 + 3으로 생각하면 좋다.
let size = CGSize(width: width, height: 1000) // cell 내에서의 문자열의 width, height은 나올 수 있는 최대 길이.
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)] // 문자열의 크기와 폰트 지정
let estimatedFrame = element.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) // 문자열의 사이즈 계산
let space = estimatedFrame.height - limit // frame값에서 여백값 빼기
print("✈️ \(space)")
return CGSize(width: width, height: 125 + space)
}
이전 프로젝트에서 건든 부분은 없습니다.
동적으로까지 구성 완료했네요!!
다음은 ReactorKit을 사용하기 위해 RxSwift로 구성해봅시다.
✅ (참고)