[iOS] Project - NuriROCK
[iOS]DiffableDatasource + Realm 구현시, Button Tag 관련
ungQ
2024. 4. 24. 23:42
기존 코드
버튼 태그 값을 이용하여 북마크 삭제 기능 구현
private func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<ResultCollectionViewCell, Bookmark> { (cell, indexPath, identifier) in
cell.updateUIInBookmarkVC(identifier)
cell.bookmarkButton.tag = indexPath.item
cell.bookmarkButton.addTarget(self, action: #selector(self.bookmarkButtonClicked), for: .touchUpInside)
cell.bookmarkButton.setImage(UIImage(systemName: "bookmark.fill"), for: .normal)
...
}
@objc private func bookmarkButtonClicked(_ sender: UIButton) {
viewModel.repository.deleteBookmarkInBookmarkView(data: Array(viewModel.outputBookmarks.value ?? [])[sender.tag])
}
private func updateSnapshot() {
var snapshot = NSDiffableDataSourceSnapshot<Section, Bookmark>()
snapshot.appendSections([.main])
let bookmarks = viewModel.outputBookmarks.value ?? []
snapshot.appendItems(bookmarks, toSection: .main)
dataSource.apply(snapshot, animatingDifferences: true) //reloadData
self.updateMapView(with: bookmarks)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3){
self.bookmarkCollectionView.reloadData()
}
}
문제점
첫 북마크의 삭제는 잘 되지만, 이후 삭제시 Button.tag들은 기존 tag 값들을 그대로 가지고 있어서 Item들의 row 값과 tag 값의 불일치 발생
시도한 방법
updateSnapshot내에 apply
대신 applySnapshotUsingReloadData
메소드를 사용하면 tag값들이 업데이트 되었지만, DiffableDataSource의 특징인 animation 효과가 사라짐
animation을 살리고자 apply
후 0.3초 후 reloadData를 호출하여 animation 효과를 살림
해결은 되었지만, DiffableDataSource를 사용하면서 reloadData 메소드를 사용하는 것은 매우 비효율적이라고 생각함
해결한 방법
cell.bookmarkButton.accessibilityIdentifier = identifier.contentid
dataSource를 정의할 때,
버튼에 tag
가 아닌 accessibilityIdentifier
에 identifier 값을 넣을 수 있었다.
indexPath 기반이 아닌, identifier을 이용하여 셀 삭제 기능을 구현하니, tag 불일치, 애니메이션 효과 등 모든 문제점이 해결 되었으며 DiffableDatasource에 더 찰떡 인 것 같다.