简体   繁体   中英

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?

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
}

Adding a target to the button inside the cellForItemAt indexPath function, also send the index path as a tag with the button function like:-

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
        }
        ...
        ...
        **cell.button.tag = indexPath.row**
        return cell
    }

Then the function in which you have set as target, you need to update that particular cell to update UI by writing the below code

[self.collectionView reloadItemsAtIndexPaths:@[Sender.tag]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM