메가커피 클론코딩을 진행하면서 UICollectionViewCompositionalLayout을 사용해 주문하기 VC를 구현하던중 상품정보를 보여줘야할 섹션에 AutoLayout이 원하는대로 배치되지 않는 문제가 발생하였다.

func productSection() -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 5, bottom: 10, trailing: 5)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(0.3))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 3)
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 15, leading: 0, bottom: 15, trailing: 0)
let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(44))
let header = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)
section.boundarySupplementaryItems = [header]
return section
}
위 코드에서 itemSize의 heightDimension과 groupSize의 heightDimension이 문제였다.
Cell의 높이를 동적으로 사용하려면 itemSize의 heightDimension과 groupSize의 heightDimension을 아래 코드와 같이 수정해주면 Cell의 높이가 동적으로 적용된다.
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .estimated(100))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100))
최종 결과

적용되지 않는 경우
1. itemSize의 heightDimension만 .fractionalHeight일 경우
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .fractionalHeight(0.3))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100))
2. groupSize의 heightDimension만 .fractionalHeight일 경우
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .estimated(100))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(0.3))
3. itemSize, groupSize 둘다 .fractionalHeight일 경우
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.3), heightDimension: .fractionalHeight(0.3))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(0.3))
'iOS' 카테고리의 다른 글
| iOS - 커스텀뷰를 테이블뷰와 비슷하게 사용하기 (0) | 2023.07.11 |
|---|---|
| iOS - 텍스트의 특정 부분만 Bold 처리하기 (0) | 2023.06.11 |
| NavigationController 사용시 status Bar Style 바꾸기 (0) | 2022.12.15 |
| navigationBar + scrollView를 함께 사용할때 top 여백 없애는 방법 (2) | 2022.12.01 |
| UINavigationBar TitleView Swipe-Back 했을때 Width 커지는 현상 (0) | 2022.10.24 |