UICollectionViewCell의 선택 오류

김세영·2022년 1월 26일
1
post-thumbnail

UICollectionView에 사진이 띄워져 있고,
이 사진을 선택하면 viewModel에 선택한 index를 알려주고,
Cell은 자신의 index가 있으면 체크마크를 띄워줌.

"삭제" 버튼을 누르면 선택한 사진이 삭제된다.

문제점

삭제를 하고 난 후 다시 사진들을 선택하려고 했는데,

어떤 것은 선택이 되지 않고
어떤 것은 선택했는데 옆 셀까지 선택되는 문제가 발생함.

온갖 삽질 끝에 원인을 발견

원인

  1. UICollectionViewUITableView는 Reuse Queue에서 Cell을 꺼내 쓴다.
  2. 바인딩은 collectionView(_:cellForItemAt:)에서 바인딩을 해줘야 한다.
  3. 1의 상황이 오면 2가 다시 호출된다.
  4. Cell과 viewModel이 다시 바인딩된다.
  5. 계속 반복;;

해결

Cell에 관련된 Cancellable을 담는 bag을 Set<AnyCancellable>이 아닌
var collectionViewCell = [UUID : AnyCancellable]로 관리하여
바인딩이 중복되지 않도록 하였다.

Cell.swift

class SomeCell: UICollectionViewCell {
    ...
    static let reuseIdentifier = "SomeCell"
    let id = UUID()
    ...
}

CollectionViewController.swift

class someCollectionViewController: UICollectionViewDataSource {
    ...
    var collectionViewBag = [UUID : AnyCancellable]()
    ...
    func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withIdentifier: SomeCell.reuseIdentifier,
                                                      for: indexPath) as! SomeCell
        
        let id = cell.id
        collectionViewBag[id] = viewModel.somePublisher
            .~
            .~
            ...
    }
    ...
}

SwiftUI는 Combine과 잘 연결되어 있어서 이런 문제가 잘 발생하지 않는다고 하는데
빨리 사용해보고 싶다

profile
초보 iOS 개발자입니다ㅏ

0개의 댓글