Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61840

How do I determine if location of my gesture recognizer is inside any view?

I simply have a wrapper UIView with following image views as subviews: A, B, C:

enter image description here

This is how I simply define tap fo my UIView:

let tapGesture = UITapGestureRecognizer()
wrapper.addGestureRecognizer(tapGesture)
tapGesture.rx.event.bind(onNext: { [weak self] recognizer in
    let subviews = self?.wrapper.subviews.filter { $0.tag == 231 } ?? []
    print("location: \(recognizer.location(in: self?.wrapper))")
    //how do I find here in what subviews my tap is located inside? Example, if I tap in area of 3, then `A, B, C`, if area of 2 then `B, C`...
}).disposed(by: bag)

Upvotes: 1

Views: 1207

Answers (1)

Sweeper
Sweeper

Reputation: 273565

Simply check if the frames of A, B, and/or C contains the point of the touch in wrapperView:

let locationInWrapper = recognizer.location(in: self?.wrapper)
if viewA.frame.contains(locationInWrapper) {
    // A is tapped
}
if viewB.frame.contains(locationInWrapper) {
    // B is tapped
}
if viewC.frame.contains(locationInWrapper) {
    // C is tapped
}

Using the same approach, you can filter the subviews rather than using 3 if statements:

let tappedViews = subviews.filter { $0.frame.contains(locationInWrapper) }

Upvotes: 1

Related Questions