Trouble Shooting

collectionView 안 텍스트 길이에 따라 동적으로 cell 사이즈 조절하기

나른한코딩 2022. 8. 22. 15:28

문자열의 사이즈에 cell의 상하좌우 inset을 더한 만큼을 cell을 그릴 때마다 width로 동적으로 할당하도록 flowLayout을 설정하였다.

코드는 아래와 같다.

 

 

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let topBottomInset: CGFloat = 10
        let leadingTrailingInset: CGFloat = 20
        let cellHeight: CGFloat = 44 + (topBottomInset * 2)
        
        let category = testCategoryList[indexPath.row]
        let size: CGSize = .init(width: collectionView.frame.width - 10, height: cellHeight)
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: .regular)]
        
        let estimatedFrame = category.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        let cellWidth: CGFloat = estimatedFrame.width + (leadingTrailingInset * 2)
        
        return CGSize(width: cellWidth, height: cellHeight)
    }
}

 

 

 

실행 결과는 아래와 같다.

 

반응형