UICollectionView
에 사진이 띄워져 있고,
이 사진을 선택하면 viewModel
에 선택한 index를 알려주고,
Cell
은 자신의 index가 있으면 체크마크를 띄워줌.
"삭제" 버튼을 누르면 선택한 사진이 삭제된다.
삭제를 하고 난 후 다시 사진들을 선택하려고 했는데,
어떤 것은 선택이 되지 않고
어떤 것은 선택했는데 옆 셀까지 선택되는 문제가 발생함.
온갖 삽질 끝에 원인을 발견
UICollectionView
및 UITableView
는 Reuse Queue에서 Cell을 꺼내 쓴다.collectionView(_:cellForItemAt:)
에서 바인딩을 해줘야 한다.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과 잘 연결되어 있어서 이런 문제가 잘 발생하지 않는다고 하는데
빨리 사용해보고 싶다