'GestureRecognizer in scrollView not working
I moved all my UIElements in a scrollView to avoid a loaded UIViewcontroller. But now the GestureRecognizers on the view does not work anymore.
My View hierarchy looks like this:
- UIViewController (SingleEventController)
- UIScrollView (EventScrollView)
- UIView (contentView)
- UILabel, UIView, UITableView, etc.
This looks like a common problem because I found quite much on Stackoverflow like: Example 1 Example 2. Still, I was not able to solve my case..
Simplified code in my EventScrollView looks like this:
let locationLabel: UILabel = {
let label = UILabel()
label.text = "Standort"
label.isUserInteractionEnabled = true //Important!
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.isUserInteractionEnabled = true //not needed!
contentView.isUserInteractionEnabled = true //Important!
}
func setupViews() {
guard let parent = parentVC else { return }
let locationTap = UITapGestureRecognizer(target: parent, action: #selector(parent.openInGoogleMaps))
locationTap.cancelsTouchesInView = false //Important!
addSubview(contentView)
contentView.addSubview(locationLabel)
locationLabel.addGestureRecognizer(locationTap)
}
What step am I missing?
Btw, clicks on a row of a UITableView
inside the contentView don't get registered either.
Solution 1:[1]
I found my issue in the comments of this Answer. The contentView inside my scrollView which got all the other views in it, had 0 height and so-on it could not be clicked. By giving the view a height, it worked:
contentView.heightAnchor.constraint(equalTo: self.frameLayoutGuide.heightAnchor, multiplier: 1).isActive = true
Solution 2:[2]
In my case, I had a UIView (Content view) into a UIScrollView, this UIView had an UIStackView into itself and then differents UIView's (like buttons) embedded into UIStackView, every one component had a height property except content view (UIView), so setting height property based on child component (UIStackView) worked for me!
splitItAllMainView.heightAnchor.constraint(equalTo: self.splitItAllStackView.heightAnchor, multiplier: 1).isActive = true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Noodledew |
Solution 2 | David Alvarado |