collectionview에 button을 넣으면 delegate가 안먹힌다..😱 delegate 대신 handler를 사용하여 클릭 이벤트를 구현해보자.
class NumberCell: UICollectionViewCell{
@IBOutlet weak var numberButton: UIButton!
var clickButtonTapHandler: (() -> Void)? // ---> 추가
func updateHidden(){
numberButton.isHidden = true
}
func updateUI(_ num: Int){
numberButton.setTitle(String(num), for: .normal)
}
// ---> 추가
// IBAction 연결
@IBAction func clickButtonTapped(_ sender: Any) {
// 버튼 클릭시 clickButtonTapHandler 호출
clickButtonTapHandler?()
}
}
extension GameViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = numberCollectionView.dequeueReusableCell(withReuseIdentifier: "NumberCell", for: indexPath) as? NumberCell else { return UICollectionViewCell() }
if cellisHidden[indexPath.item] == 1 {
cell.updateHidden()
} else {
cell.updateUI(indexPath.item + 1)
}
// ---> clickButtonTapHandler 정의
cell.clickButtonTapHandler = {
if self.cellisHidden[indexPath.item] == 0{
NotificationCenter.default.post(name: self.ClickNumberNotification, object: nil, userInfo: ["num" : indexPath.item + 1])
}
}
return cell
}
}