0

I have a switch in a custom view on a custom UICollectionViewCell. If I can correlate switch's toggle action with UICollectionViewCellDelegate's didSelectRow method, I can know both the switch's condition and cell's indexPath.

Here is an example what i am trying to.

class CustomCellView: UIView {
    private(set) var toggleSwitch = UISwitch()

    // Initializers and other customizations
}
class CustomCell: UICollectionViewCell {

    // Initializers and other customizations

    func setView(view: UIView) {
        self.contentView = view
    }
}
class CustomVC: UIViewController, UICollectionViewDelegate {
    // Some lifecycle operations

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) as? CustomCell,
              let view = cell.contentView as? CustomView else { return }
        var isOn = view.toggleSwitch.isOn

        // Do some stuffs with this attribute
    } 
}

I want to call didSelectItemAt method of collectionViewDelegate when the switch condition is changed.

I used delegate pattern to figure out any changes on this switch's isOn property but I need also cell's indexPath to act for specific cases.

KosFM
  • 1
  • 4

1 Answers1

1

You can write a custom protocol method, so you can invoke the function inside that protocol when the user interacts with the toggle button.

here is the sample code

custom protocol protocol MyCollectionViewCellDelegate: AnyObject { func didToggleUpdated(_ cell: MyCollectionViewCell) }

use the protocol function on toggle action (inside the collection view cell)

class MyCollectionViewCell: UICollectionViewCell {
    

    var toggleSwitch = UISwitch()
    weak var delegate: MyCollectionViewCellDelegate?
    
    override func awakeFromNib() {
        super.awakeFromNib()

        toggleSwitch.addTarget(self, action: #selector(toggleSwitchValueChanged), for: .valueChanged)
    }
    
    @objc private func toggleSwitchValueChanged() {
        delegate?.didToggleUpdated(self)
    }
}

inside the collection view cellforItems

cell.delegate = self

write an extension for the view controller CustomVC then you will get the call back of the toggle action

extenstion CustomVC: MyCollectionViewCellDelegate {
    func didToggleUpdated(_ cell: MyCollectionViewCell) {
       guard let cell = collectionView.indexPath(for: cell) else { return }
    //do the stuff here

    }
}