[iOS] UICollectionView - 1

Yong-Tae Kwon·2021년 3월 3일
0

ios

목록 보기
1/2

iOS에서 기본적인 view를 구성할 때 가장 빈번하게 사용되는 UICollectionview에 대해서 알아봅니다.

1. Collection View란?

class UICollectionView: UIScrollView
class UICollectionViewController: UIViewController

  • Collection View는 정렬된 data item을 관리하고, 커스텀화한 layout을 활용해 데이터들을 보여주기 위한 객체이다.

2. Collection View의 Data

1) dataSource ⭐️⭐️⭐️

var dataSource: UICollectionViewDataSource

  • data와 data를 보여주는 view에대한 object를 제공

Required

  1. func collectionView(UICollectionView, numberOfItemsInSection section: Int) -> Int

    • section당 item의 개수를 return
  2. func collectionView(UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

    • IndexPath에 해당하는 item을 return
    • 여기서 item을 configure 해서 return 해주어야한다.
    • dequeueReusableCell(withReuseIdentifier:for:)를 호출한다. (무조건 cell을 리턴함.)
    • 이 메소드를 사용하기 전에 identifier를 class나 nib파일을 활용해 등록해야 한다.
    • isPrefetchingEnabled라는 변수가 true로 설정되어있는 경우, prefetch가 가능하다.

Optional

  1. func numberOfSections(in: UICollectionView) -> Int

    • section의 개수를 return
  2. func collectionView(UICollectionView, viewForSupplementaryElementOfKind: String, at: IndexPath) -> UICollectionReusableView

    • 표시할 supplementary view를 return
  3. func collectionView(UICollectionView, canMoveItemAt: IndexPath) -> Bool

    • 어떤 아이템이 collection view의 다른 위치로 이동할 수 있는지 return
  4. func collectionView(UICollectionView, moveItemAt: IndexPath, to: IndexPath)

    • 어떤 아이템을 새로운 특정 위치로 이동시키도록 한다.
  5. func indexTitles(for: UICollectionView) -> [String]?

    • collection View에 표시할 title들을 리턴한다.
  6. func collectionView(UICollectionView, indexPathForIndexTitle: String, at: Int) -> IndexPath

    • indexPathForIndexTitle과 일치하는 indexPath 찾아서 return

2) dataSource Prefetch

protocol UICollectionViewDataSourcePrefetching

  • prefetch는 cell이 실제로 화면에 표시되기 전에 dataSource를 미리 준비해주는 메커니즘이다.
  • 일반적으로 모든 데이터가 다 준비되었을 때 필요한 것이 아니라, 느리고 비용이 많이 드는 과정을 통해서 (ex. http통신) 데이터를 fetch해야할 때 쓰는 것이 바람직하다.
  1. (당연히) Collection View와 Collection View의 기본 data source를 구현한다.
  2. UICollectionViewDataSourcePrefetching protocol을 채택하는 object를 구현하고, prefetchDataSource 속성에 할당한다.
  3. func collectionView(UICollectionView, prefetchItemsAt: [IndexPath]) method를 구현한다. 이 메소드는 collection View가 화면에 로드되고 셀을 로드할 준비가 끝나면 호출이 된다. 이 메소드에서 데이터를 비동기적으로 fetch한다.
    • cell이 아니라 cell에 보여지는 data source 준비하게 도와준다.
    • 자동으로 호출시점을 조정한다.
    • 다음 예시와 같이 쓸 수 있겠다.
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
    for indexPath in indexPaths {
        self.fetchData(index: indexPath.row) 
    }
}
  1. func collectionView(UICollectionView, cellForItemAt: IndexPath)에서 prefetch된 데이터를 활용하여 cell을 보여줄 준비를 한다.
  2. func collectionView(UICollectionView, cancelPrefetchingForItemsAt: [IndexPath]) 메소드는 prefetch된 데이터가 필요없어졌을 때 (역 스크롤링 등) 호출되는 optional method다. 필요없어진 데이터를 정리해주면 된다.

3. Collection View의 Cell

1) cell (class UICollectionViewCell)

  • Collection View의 visible bound안에 있는 data item 하나
  • UICollectionReusableView을 상속
  • cell의 view에 접근 가능
    1. var contentView: UIView
    2. var backgroundView: UIView?
    3. var selectedBackgroundView: UIView?
  • cell state
    1. var isSelected
    2. var isHighlighted
  • drag state의 변경 감지 가능
    1. func dragStateDidChange(UICollectionViewCell.DragState)
    2. drag state: enum UICollectionViewCell.DragState
      • .none
      • .lifting
      • .dragging

2) class UICollectionReusableView: UIView

  • Collection View의 모든 cellsupplementary views를 정의하는 view
  • 특히 cell은 이것을 상속해서 정의하게 된다.
  • Reusable의 의미에 대해서는 나중에 알아보도록 하자.

3) register

  • cell을 사용하기 전에 register과정을 거쳐서 그려질 UI를 등록해야한다. (Nib or Class 활용)
  1. func register(AnyClass?, forCellWithReuseIdentifier: String)
    • 새로운 Collection View Cell을 만들 때 사용할 class를 등록한다.
  2. func register(UINib?, forCellWithReuseIdentifier: String)
    • 새로운 Collection View Cell을 만들 때 사용할 Nib file을 등록한다.
  3. func register(AnyClass?, forSupplementaryViewOfKind: String, withReuseIdentifier: String)
    • 새로운 supplementary view를 만들때 사용한 class를 등록한다.
  4. func register(UINib?, forSupplementaryViewOfKind: String, withReuseIdentifier: String)
    • 새로운 supplementary view를 만들때 사용한 Nib file을 등록한다.

4) dequeue reusable View

  1. func dequeueReusableCell(withReuseIdentifier: String, for: IndexPath) -> UICollectionViewCell
    • 이 메소드는 사용 가능한 cell이 존재하면 dequeue하고, 아니면 새로운 cell을 create한다.
      • 재사용 가능한 cell이 있는 경우 --> cell을 dequeue해 사용하기 전 prepareForReuse() 호출
      • 재사용 가능한 cell이 없는 경우 --> cell을 init()
  2. func dequeueReusableSupplementaryView(ofKind: String, withReuseIdentifier: String, for: IndexPath) -> UICollectionReusableView
    • Returns a reusable supplementary view located by its identifier and kind.

5) cell preFetch

  • cell도 data와 마찬가지로 더 나은 scroll experience를 위해서 display 되기전에 fetch가 일찍 필요하다.
  • default 설정이 enable하게 되어있다.
profile
To Infinity, and Beyond!

0개의 댓글