ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • cellForItemAt: 에서 select 해주기
    iOS 2020. 4. 24. 16:07

    cell이 select 되었을 때 셀에 어떤 처리를 해주는 경우가 많이 있죠.

    cellForItemAt: 에서 원하는 cell을 select 해주려면 어떻게 해야할까요?


    접근

    먼저 select를 처리해주는 방법부터 알아볼까요?

    delegate를 이용해 didSelectedItemAt 에서 처리해주는게 가장 대표적이지만 현재 목표와는 맞지 않습니다.

    다른 방법으로 cell 자체의 isSelected 를 이용해 isSelected의 값이 변할 때마다 처리를 해주는 방법을 사용해야겠습니다.

    활용

    오늘은 collectionView의 cell을 선택하면 색이 바뀌는도록 만들어볼게요 :)

    먼저 MyCollectionViewCell 을 만들어주고 거기서 isSelect 를 override 해서 색의 색을 바꿔줍니다.

    // ViewController.swift
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? MyCollectionViewCell else {return UICollectionViewCell()}
      cell.backgroundColor = .orange
      return cell
    }
    
    
    // MyCollectionViewCell.swift
    override var isSelected: Bool {
      didSet {
        if isSelected {
            backgroundColor = .blue
        } else {
            backgroundColor = .orange
        }
      }
    }

    선택된 셀은 파란색 아니면 오렌지색이 되겠네요.

    일단 이상태로 두고 실행시켜볼까요?

    네 우선 선택은 잘 되네요!!

    그럼 이제 cellForItemAt 에서 원하는 셀에 isSelect = true 로만 설정해주면 되는거 아닐까요?!

    저는 첫번째 셀을 선택해볼게요.

    // ViewController.swift
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? MyCollectionViewCell else {return UICollectionViewCell()}
      cell.backgroundColor = .orange
      if indexPath.item == 0 {
        cell.isSelected = true
      }
      return cell
    }

    오 원하는대로 됐..... 네 되는 듯 했으나 처음에 선택해준 셀이 제대로 deselect 되지 않는 문제가 있습니다.

    검색해본 결과 collectionView는 multiple selection을 허락하지 않기 때문에 이미 선택되어 있는 셀은 제대로 deselect하지 않는다는 글을 봤는데 이게 가장 신빙성 있는 원인인 것 같더라구요. 하지만 그렇다고 multiple selection을 사용하고 싶지 않은데 이걸 위해서 바꿔버리면 좀 찝찝하겠죠??

    다른 해결책으로, isSelect = true 와 함께 collectionView의 selectItem도 해주는 방법이 있습니다.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? MyCollectionViewCell else {return UICollectionViewCell()}
      cell.backgroundColor = .orange
    
      if indexPath.item == 0 {
        cell.isSelected = true
        collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .init())
      }
    
      return cell
    }

    이렇게 해주면 원하는 대로 동작합니다 👏👏

    최고의 방법인지는 모르겠지만 제가 원하는 동작에 가장 근접한 방법인 것 같네요.

    더 좋은 방법이 있다면 포스팅해야겠어요 :)

    도움이 되셨으면 좋겠습니다!

    댓글

Designed by Tistory.