Home > Blockchain >  How to make the background view of a collectionView pass taps below
How to make the background view of a collectionView pass taps below

Time:11-15

I'm building a collectionview. Below of it I placed some buttons as shown in the picture. What I want is to make the UICollectionView background pass taps below, so the desired buttons can receive taps.

I don't need to add Tap gesture recognizers to the background view (the problem I'm describing is just an example here), I need the buttons' actuons to be triggered directly when they're tapped.

I thought I could do this by making the background clear or disabling user interaction for the background view. While disabling it for the entire collection view works, this other way does not. How can I make the background view of my collectionView be "invisible" so that taps go straight to the below buttons instead of going to the collectionview background?

The following is an example of my layout.

enter image description here

CodePudding user response:

Assuming your collectionView and your buttons share the same superview, this should do the trick.

What you want to do is bypass the backgroundView and forward hits to the subviews underneath the collectionView.

Notice that we are picking the last subview with the matching criteria. That is because the last subview in the array is the closest to the user's finger.

class SiblingAwareCollectionView: UICollectionView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        let hit = super.hitTest(point, with: event)
        guard hit === backgroundView else {
            return hit
        }

        let sibling = superview?
            .subviews
            .filter { $0 !== self }
            .filter { $0.canHit }
            .last { $0.point(inside: convert(point, to: $0), with: event) }

        return sibling ?? hit
    }
}

If you look at the documentation for hitTest(_:with:) it says:

This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01.

For convenience, here is an extension to ensure we are playing by the rules:

extension UIView {
    var canHit: Bool {
        !isHidden && isUserInteractionEnabled && alpha >= 0.01
    }
}
  • Related