I had a lot of trouble getting subviews in a view to respond to touches. This is a really simple and I have don't it a lot of times. But in this particular case I was adding a lot of subviews to my main view and adding recognisers programmatically.
The problem - after adding about 20 subviews to my main view and adding UITouchRecognizers to all of them, the subviews were not responding to touch (none except ONE subview). The subviews are totally non-overlapping (I can re-create the issue with even just 2 subviews)
All subviews are UIImageViews and I was setting userInteraction enabled. Here is the code that did not work:
let recognizer = UITapGestureRecognizer(target: self, action: "tapResponse:")
for n in (1...20) {
let node = UIImageView(image:UIImage(named: "pic.png"))
node.userInteractionEnabled = true node.addGestureRecognizer(recognizer)
view.addSubView(node)
}
I finally figured out a fix for my problem after a lot of experimenting.
The code above will add the same instance of UITapGestureRecognizer to every view. This seems to be a problem - only the last node gets the recognizer. All the rest do not respond to tap. The code below creates and adds a new recognizer object for each subview. It works - all nodes when tapped respond (i.e. call the handler)
for n in (1...20) {
let node = UIImageView(image:UIImage(named: "pic.png"))
node.userInteractionEnabled = true
let recognizer = UITapGestureRecognizer(target: self, action: "tapResponse:")
node.addGestureRecognizer(recognizer) view.addSubView(node)
}
The question:
Why cant I create it like the original code i.e. add the same recogniser object for multiple views ? Can the same recognizer object not be added to all node views?