Search code examples
iosxcodeuikitswift4uicollectionviewcell

How do I create an action that changes the properties of a specific uicollectionviewcell?


I have an app with a UICollectionView. Each custom cell has a circular progress view and a button that's supposed to up its progress, but I can't figure out how to change the properties for the specific cell's subviews inside the button action.

I've tried

  • adding a target to the button inside the "cellForItemAt indexPath" function, but then how to call for that specific cell inside the target's function.

  • adding a IBAction inside the custom cell class, but same problem again

Basically the problem is how can you call for a specific cell at a certain index path outside the "cellForItemAt" function?


Solution

  • You can setup your UICollectionViewCell subclass something like this:

    class MyCollectionViewCell: UICollectionViewCell {
    
        @IBOutlet weak var button: UIButton!
        @IBOutlet weak var progressView: UIProgressView!
    
        var buttonAction: (() -> Void)?
    
        @IBAction func didPressButton() {
            buttonAction?()
        }
    
    }
    

    and in your UITableViewDelegate

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "your identifier", for: indexPath) as! MyCollectionViewCell
        cell.buttonAction = {
            //Do whatever you wish
        }
        ...
        ...
        return cell
    }