collectionView(shouldSelectItemAt:)을 사용하여 collectionView의 cell touch시 어떻게 이벤트를 처리할 것인지 설정할 수 있습니다.
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let cell = collectionView.cellForItem(at: indexPath) as? CustomCell else {
return true
}
if cell.isSelected {
collectionView.deselectItem(at: indexPath, animated: true)
return false
} else {
return true
}
}
위의 코드는 cell이 선택되었을 때, 만약 해당 index의 cell이 선택상태라면, 그 cell을 deselect시킨 후 false를 리턴하여 선택되는 것을 방지하고, 선택상태가 아니라면 그냥 selected를 허용하겠다는 의미입니다.
collectionView(didSelectItemAt:)와의 차이점은 호출 시점의 차이 입니다. 이 메서드는 마치 property observer의 didSet처럼 변화가 발생된 이후에 호출되는 메서드입니다.