swift

Dynamic Cell Size CollectionView

motosw3600 2022. 1. 25. 22:23

cell안의 Label크기에 따른 Dynamic Cell Resizing

 

systemLayoutSizeFitting사용

systemLayoutSizeFitting이란?

  • 제약조건과 지정된 우선순위에 따라 최적의 View크기를 반환한다.
  • constraint가 설정된 상황에서 사용가능

parameter

  • targetSize
    • 선호하는 크기를 지정한다.
    • 가능한 큰 크기의 View를 얻으려면 layoutFittingExpandedSize사용
    • 가능한 작은크기의 View를 얻으려면 layoutFittingCompressedSize사용
  • horizontalFittingPriority
    • 수평 constraints를 설정. fittingSizeLevel을 사용하면 targetSize의 width와 비슷한 width로 설정
  • verticalFittingPriority
    • 수직 constraints를 설정. fittingSizeLevel을 사용하면 targetSize의 height와 비슷한 height로 설정

systemLayoutSizeFitting을 사용한 cellSize 반환

// CollectionViewCell
func adjustCellSize(height: CGFloat, label: String) -> CGSize {
    self.tagLabel.text = label
    let targetSize = CGSize(width: UIView.layoutFittingCompressedSize.width, height:height)
    return self.contentView.systemLayoutSizeFitting(targetSize,
                                                    withHorizontalFittingPriority:.fittingSizeLevel,
                                                    verticalFittingPriority:.required)
}

 

FlowLayoutDelegate를 사용한 CellSize설정

// UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    guard let cell = collectionView.dequeueReusableCell(
        withReuseIdentifier: TagCollectionViewCell.identifier, for: indexPath
    ) as? TagCollectionViewCell else { return .zero }
    return cell.adjustCellSize(height: 45, label: tags[indexPath.item])
}

 

'swift' 카테고리의 다른 글

DispatchSemaphore  (0) 2022.02.06
UICollectionView Custom Layout  (0) 2022.02.03
Tabbar Paging With CollectionView  (0) 2022.01.25
Carousel Effect  (0) 2022.01.22
Image Optimizing  (0) 2022.01.18