-1

I have a UIViewController which has 4 UICollectionViews. Each CollectionView uses the same custom cell, via its NIB. Each cell has buttons on it, whose actions are defined using the delegate structure.

In my main View Controller, I've implemented UITapGesture to get the coordinates of taps on screen. However, UITapGesture fails to log the coordinates when the button is tapped (presumably because it's not the responder).

I'd like to know if there's a way that I can get the Button's onscreen coordinates relative to the main view.

I tried overriding touchBegan but that also failed.

Is there any way I can have multiple actions triggered by the delegate button? I.e. have it's function triggered while also recording the onscreen location of the tap?

Karim
  • 271
  • 2
  • 11

1 Answers1

0

You don't need UITapGesture:

On cellForItemAt store a unique identifier as a string inside a variable. You can also set the IndexPath (But you have multiple CollectionViews) or you can set a unique tag to your UIButton.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCell.identifier, for: indexPath) as! MyCell
    cell.buttonIdentifier = "Cell-XY"
}

// Delegate
func didTapOnMyButton(with identifier: String) {
    switch identifier {
    case "Cell-XY": // is button "Cell-XY"
    default: // can'z happend, but handle that too
    }
}



class MyCell: UICollectionViewCell {
    static let identifier = "MyCell"

    var buttonIdentifier = ""

    @objc didTapOnMyButton() {
        delegate?.didTapOnMyButton(with: buttonIdentifier)
    }


    override func prepareForReuse() {
        super.prepareForReuse()
        buttonIdentifier = ""
    }
}
A. Amini
  • 521
  • 8
  • 15