Anton Belousov
Anton Belousov

Reputation: 1141

Custom hit-test on UICollectionViewCell

I have chat UI based on UICollectionView. Very common UI that looks like iMessage. I have logic that handles taps on chat message bubbles using

collectionView(_:didSelectItemAt:)

I want to add tap gesture recognizer to the background of this collection view to dismiss keyboard.

So I want to customize hit testing on my bubbleCell, so I will be able to tap on bubble to call

collectionView(_:didSelectItemAt:)

and to tap on empty space to call close keyboard logic.

What should I do to achieve this behaviour?

Upd. Some code

If I add tap gesture to the ChatViewController.view

func viewDidLoad() {
    // ...
    let tap = UITapGestureRecognizer(target: self, action: #selector(ChatViewController.dismissKeyboard))
    self.view.addGestureRecognizer(tap)
}

func dismissKeyboard() {
    self.view.endEditing(true)
}

This code will never being called

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // Handle tap on cell
}

Upvotes: 1

Views: 1079

Answers (1)

toddg
toddg

Reputation: 2906

I think you'll need to set cancelTouchesInView to false on your UITapGestureRecognizer in order to recognize both taps (on Collection View and your Tap Gesture Recognizer).

let tap = UITapGestureRecognizer(target: self, action: #selector(ChatViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)

Upvotes: 1

Related Questions