๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿงฏ Troubleshooting

[Cheliz] UICollectionViewCell ๋‚ด ๊ฐ์ฒด์˜ action ์ฒ˜๋ฆฌ

// SearchCollectionViewCell

// MARK: - Properties
    var media: Media?
    var addErrorHandler: (() -> Void)?
    var addCompletionHandler: (() -> Void)?

// MARK: - Action Methods
    private func setAddButtonAction() {
        addButton.addTarget(self, action: #selector(addButtonClicked), for: .touchUpInside)
    }
    
    @objc private func addButtonClicked() {
        if let media = media, let addErrorHandler = addErrorHandler, let addCompletionHandler = addCompletionHandler {
            let repository = MediaRepository()
            repository.add(media: media, completionHandler: addCompletionHandler, errorHandler: addErrorHandler)
        }
    }

Button Action - Cell์—์„œ ์ฒ˜๋ฆฌ

 

 

// SearchViewController

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SearchCollectionViewCell.reuseIdentifier, for: indexPath) as? SearchCollectionViewCell else {
        print("Cannot find SearchCollectionViewCell")
        return UICollectionViewCell()
    }
    
    cell.media = searchResults[indexPath.row]
    cell.addErrorHandler = { self.alert(title: "์˜ค๋ฅ˜ ์•ˆ๋‚ด", message: "์ถ”๊ฐ€์— ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”.") }
    cell.addCompletionHandler = { self.searchView.makeToast("์„ฑ๊ณต์ ์œผ๋กœ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.", duration: 1, position: .center) }
    cell.showResult {
        self.alert(title: "์˜ค๋ฅ˜ ์•ˆ๋‚ด", message: "๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
    }
    
    return cell
}

 

Button Action - View Controller์—์„œ ์ฒ˜๋ฆฌ

 

 

 

์œ„์™€ ๊ฐ™์ด ๊ฐ ์…€์˜ ์ถ”๊ฐ€ ๋ฒ„ํŠผ์— ๋Œ€ํ•œ ์•ก์…˜ ์ฒ˜๋ฆฌ๋ฅผ Collection View Cell ํด๋ž˜์Šค์—์„œ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„์ง€, ์•„๋‹ˆ๋ฉด View Controller์˜ cellForItemAt ๋ฉ”์„œ๋“œ ์•ˆ์—์„œ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„์ง€ ๊ณ ๋ฏผ์ด ๋œ๋‹ค.,,

 

 

 

 

์ถ”๊ฐ€ ๋ฒ„ํŠผ
์•ก์…˜
Cell์—์„œ ์ฒ˜๋ฆฌ View Controller์—์„œ ์ฒ˜๋ฆฌ
์žฅ์  ๊ฐ Cell ์•ˆ์˜ ์˜ค๋ธŒ์ ํŠธ(๋ฒ„ํŠผ)์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. Handler Closures๋ฅผ ๋„˜๊ฒจ์ค„ ํ•„์š”๊ฐ€ ์—†์–ด ์˜ต์…”๋„ ๋ฐ”์ธ๋”ฉ์˜ ๊ณผ์ •์„ ์ƒ๋žตํ•  ์ˆ˜ ์žˆ๋‹ค.
๋‹จ์  Handler Closures๋ฅผ View Controller์—์„œ
Cell๋กœ, ๊ทธ๋ฆฌ๊ณ  Realm Repository๊นŒ์ง€ ๋„˜๊ฒจ ์ฃผ์–ด์•ผ ํ•˜๊ณ , ์•ก์…˜ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜์—์„œ ์˜ต์…”๋„ ๋ฐ”์ธ๋”ฉ์ด ๊ณผ๋„(?)ํ•˜๊ฒŒ ๋ฐœ์ƒํ•œ๋‹ค.
cellForItemAt ํ•จ์ˆ˜๊ฐ€ ๊ธธ์–ด์ง€๊ณ , Cell ๋‚ด๋ถ€ ์˜ค๋ธŒ์ ํŠธ(๋ฒ„ํŠผ)์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ์˜ ๊ตฌ๋ถ„์ด ํ๋ ค์ง„๋‹ค.