스토리보드로 컬렉션 뷰 셀 구현
셀 클래스 내에서 델리게이트 구현
protocol ReviewPhotoCellDelegate: AnyObject {
func didTabDeleteButton(in cell: UICollectionViewCell)
}
class ReviewPhotoCell: UICollectionViewCell {
weak var delegate: ReviewPhotoCellDelegate?
@IBOutlet weak var reviewPhotoImageView: UIImageView!
@IBOutlet weak var deleteButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
reviewPhotoImageView.layer.cornerRadius = 2
}
override func prepareForReuse() {
super.prepareForReuse()
}
func setupReviewPhoto(image: UIImage) {
reviewPhotoImageView.image = image
}
@IBAction func didTabDeleteButton(_ sender: Any) {
delegate?.didTabDeleteButton(in: self)
}
}
컬렉션뷰 데이터 소스 구현
extension RestaurantDetailViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel?.reviewImages.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReviewPhotoCell", for: indexPath) as? ReviewPhotoCell else { return UICollectionViewCell() }
cell.delegate = self
cell.setupReviewPhoto(image: viewModel?.reviewImages[indexPath.row] ?? UIImage())
return cell
}
}
ReviewPhotoCellDelegate 구현
extension RestaurantDetailViewController: ReviewPhotoCellDelegate {
func didTabDeleteButton(in cell: UICollectionViewCell) {
guard let indexPath = reviewPhotoCollectionView.indexPath(for: cell) else { return }
viewModel?.reviewImages.remove(at: indexPath.item)
reviewPhotoCollectionView.performBatchUpdates {
reviewPhotoCollectionView.deleteItems(at: [indexPath])
}
}
}