새벽의 기록

delegate extension, datasource extension 뭐가 뭐지? 본문

[iOS]

delegate extension, datasource extension 뭐가 뭐지?

OneTen 2024. 11. 22. 15:27

UICollectionView 사용하면서 extension으로 한 번에 delegate, datasoure 설정해주면서 사용했었다.

그런데 이번에 컨벤션으로 하나의 extension은 하나의 속성만 관리하자고 정해서 분리하려고 하니까,정작 어떤 코드가 delegate에 해당하고 어떤 코드가 datasource에 해당하는 지 모르겠어서 정리한다


1. UICollectionViewDataSource의 역할

 

UICollectionViewDataSource는 컬렉션 뷰의 데이터를 관리한다.

컬렉션 뷰에 표시할 셀과 섹션의 개수, 데이터를 셀에 전달하는 등의 작업이 여기에 들어간다.

 

주요 역할:

• 컬렉션 뷰에 표시할 데이터를 제공.

• 섹션과 아이템의 개수를 결정.

• 데이터에 따라 셀을 생성 및 구성.

 

주요 메서드:

  1. numberOfSections(in:): 컬렉션 뷰에 몇 개의 섹션이 있는지 반환.
  2. collectionView(_:numberOfItemsInSection:): 각 섹션에 몇 개의 아이템이 있는지 반환.
  3. collectionView(_:cellForItemAt:): 특정 아이템(셀)을 구성하고 반환.

어떤 코드가 들어갈까?

• 데이터를 기반으로 섹션과 아이템의 개수를 반환하는 코드.

• 특정 아이템에 해당하는 데이터를 셀에 설정하는 코드.

• 셀에 데이터를 전달하고 셀의 레이아웃을 구성하는 코드.

 

예시

extension GalleryViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 3 // 섹션 개수
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1 // 첫 번째 섹션의 아이템 개수
        case 1:
            return 5 // 두 번째 섹션의 아이템 개수
        default:
            return 10 // 나머지 섹션의 아이템 개수
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCustomCell else {
            return UICollectionViewCell()
        }
        cell.configure(with: data[indexPath.row]) // 데이터를 셀에 전달
        return cell
    }
}

 

 

2. UICollectionViewDelegate의 역할

 

UICollectionViewDelegate는 사용자 상호작용을 처리하고 뷰의 동작을 커스터마이징하는 역할을 한다.

사용자가 셀을 선택하거나 특정 요소와 상호작용했을 때 처리하는 코드를 여기에 작성.

 

주요 역할:

• 셀의 선택, 강조 표시, 강조 해제 등의 이벤트를 처리.

• 특정 셀의 크기, 레이아웃, 스크롤 동작 등을 커스터마이징.

• 헤더 및 푸터와 관련된 작업을 처리.

 

주요 메서드:

  1. collectionView(_:didSelectItemAt:): 사용자가 특정 아이템을 선택했을 때 호출.
  2. collectionView(_:didDeselectItemAt:): 특정 아이템 선택이 해제되었을 때 호출.
  3. collectionView(_:viewForSupplementaryElementOfKind:at:): 섹션 헤더나 푸터를 구성.
  4. collectionView(_:willDisplay:forItemAt:): 특정 셀이 표시되기 직전에 호출.

어떤 코드가 들어갈까?

• 사용자가 셀을 선택했을 때 동작을 정의하는 코드.

• 셀을 강조 표시하거나 선택 해제하는 동작.

• 섹션 헤더/푸터를 구성하는 코드.

• 스크롤 동작, 셀의 동적 크기 조정 등 UI 관련 동작.

 

예시

extension GalleryViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("섹션 \\(indexPath.section)의 아이템 \\(indexPath.row)가 선택되었습니다.")
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        guard kind == UICollectionView.elementKindSectionHeader else { return UICollectionReusableView() }
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "MyHeader", for: indexPath)
        // 헤더 구성
        return header
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        print("셀 \\(indexPath.row)가 화면에 나타났습니다.")
    }
}

 

정리

 

• UICollectionViewDataSource:
-> 데이터 관리와 셀/섹션 구성.
-> 항상 필수적으로 구현해야 하는 메서드 포함.

 

• UICollectionViewDelegate:
-> 사용자 상호작용과 UI 커스터마이징.
-> 선택적으로 구현 가능하며 이벤트 중심 작업 처리.

'[iOS]' 카테고리의 다른 글

[ios\swift] SwiftUI TextField 글자 수 제한  (0) 2024.08.06
[ios\swift] 고차함수 (map, filter, reduce)  (0) 2024.06.11
[ios\swift] allSatisfy(_:)  (0) 2024.06.10
[ios\swift] 내장함수 zip(_:_:)  (0) 2024.05.28
Comments