Skip to content

collectionView cell의 최적화 크기 찾기

DOHYUN CHUNG edited this page Sep 7, 2022 · 1 revision

CollectionView Cell의 동적인 크기

CollectionView Cell의 크기를 사진과 글에 맞추어 동적으로 변경하고 싶었다. CollectionView Cell의 크기를 내용에 맞추어 동적으로 변경하는 방법은 다양하다. 그 중에 사용했던 방식은 systemLayoutSizeFitting 메서드를 사용하는 것이다.

func systemLayoutSizeFitting(_ targetSize: CGSize) -> CGSize

Returns the optimal size of the view based on its current constraints

결국 현재 constraint에서 가장 최적화된 사이즈를 반환한다는 의미의 함수이다. 이 함수를 사용하기 위해서 필요한 것은 cell의 contentView의 leading, trailing은 autolayout이 잡혀있어야한다는 것이다.

systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority:)

이 함수가 위의 함수에서 2가지 parameter가 더 존재한다. withHorizontalFittingPriority는 너비값을 우선순위로 둔다. 그렇기 때문에, targetSize의 넓이와 가장 비슷한 CGSize를 찾기 위해서는 priority를 fittingSizeLevel을 설정해준다. 반면에 verticalFittingPriority 높이값을 우선순위로 두는것이다. horizontal과 마찬가지로 설정할 수 있다.

MOMO에서 사용한 방법

MOMO에서는 default로 cellheight를 찾을 수 있도록 findCellHeight라는 메서드를 구현한다. 더미 데이터를 넣어서 cellheight을 대략적으로 구하는 것이다. 이 cell을 targetSize로 둔다. targetSize의 세로의 최적화 크기를 구하는 것이기 때문에, targetSize의 CGSize를 구할 때, height을 intrincsicContentSize 에 딱 맞도록 최소 크기를 위해서 layoutFittingCompressedSize 를 사용해서 설정한다.

static func fittingSize(width: CGFloat) -> CGSize {
    let cell = RecommendCollectionViewCell()
    cell.findCellHeight()
    let targetSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)
    return cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
  }

  func findCellHeight(title: String = "[필독] 임산부가\n 주의해야할 약 10가지") {
    thumbNailImageView.image = UIImage.colorImage(color: Asset.Colors.pink5.color.cgColor, size: self.frame.size)
    titleLabel.text = title
  }