apple/iOS, UIKit, Documentation

UICollectionView에 대해서 알아보기 3편 (동적 Cell)

lgvv 2022. 8. 22. 22:20

[iOS] UICollectionView에 대해서 알아보기 3편 (동적 Cell)

 

동적으로 UICollectionView Cell을 구성해야 하는데, 아직까지 초보자라서 이거 많이 어렵다.

구글링을 통해 다른 사람이 구현한 프로젝트 코드 Stackoverflow 등 엄청나게 많이 예제들을 참고했다.

 

구현 방향성

  • DummyCell을 사용한 방법 (가장 많이 보이는 패턴이었음)
    • 이 형태를 연습해보고자 함.

 

(2023.01.17 추가)

 

동적셀 요즘은 구현하기가 어렵지 않는데, 그냥 데이터에서 미리 사이즈를 모두 계산하고 처리함.

일부만 동적인 경우가 있어서 하다보니 익숙해진 부분도 크다.

 

 

소스코드

AppleCollectionView.zip
2.64MB

 

🌿 결과물 🌿

동적인 셀 결과물

 

샘플 코드

    /// 셀의 레이아웃 정보를 구성
    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)
    }

 

 

 

 

✅ (참고)

https://blog.naver.com/PostView.naver?blogId=greatsk553&logNo=221203116193&redirect=Dlog&widgetTypeCall=true&directAccess=false 

 

ios swift cell의 크기에 맞게 자동으로 늘어나는 UICollectionView 만들기

cell의 크기에 맞게 동적으로 늘어나는 UICollectionView를 만들거다. 먼저 UICollectionViewDele...

blog.naver.com