I\'m new to gesture recognizers so maybe this question sounds silly: I\'m assigning tap gesture recognizers to a bunch of UIViews. In the method is it possible to find out w
You can also use "shouldReceiveTouch" method of UIGestureRecognizer
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch: (UITouch *)touch {
UIView *view = touch.view;
NSLog(@"%d", view.tag);
}
Dont forget to set delegate of your gesture recognizer.
If you are adding different UIGestureRecognizer
on different UIView
s and want to distinguish in the action method then you can check the property view in the sender parameter which will give you the sender view.
You should amend creation of the gesture recogniser to accept parameter (add colon ':')
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
And in your method highlightLetter: you can access the view attached to recogniser:
-(IBAction) highlightLetter:(UITapGestureRecognizer*)recognizer
{
UIView *view = [recognizer view];
}
Use this code in Swift
func tappGeastureAction(sender: AnyObject) {
if let tap = sender as? UITapGestureRecognizer {
let point = tap.locationInView(locatedView)
if filterView.pointInside(point, withEvent: nil) == true {
// write your stuff here
}
}
}
Say you have a FaceView
which is some sort of image. You're going to have many of them on screen (or, in a collection view, table, stack view or other list).
In the class FaceView
you will need a variable "index"
class FaceView: UIView {
var index: Int
so that each FaceView can be self-aware of "which" face it is on screen.
So you must add var index: Int
to the class in question.
So you are adding many FaceView to your screen ...
let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.
You now add a click to f
f.addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(tapOneOfTheFaces)))
@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
if let tapped = sender.view as? CirclePerson {
print("we got it: \(tapped.index)")
You now know "which" face was clicked in your table, screen, stack view or whatever.
It's that easy.
Swift 5
In my case I needed access to the UILabel that was clicked, so you could do this inside the gesture recognizer.
let label:UILabel = gesture.view as! UILabel
The gesture.view property contains the view of what was clicked, you can simply downcast it to what you know it is.
@IBAction func tapLabel(gesture: UITapGestureRecognizer) {
let label:UILabel = gesture.view as! UILabel
guard let text = label.attributedText?.string else {
return
}
print(text)
}
So you could do something like above for the tapLabel function and in viewDidLoad put...
<Label>.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(tapLabel(gesture:))))
Just replace <Label>
with your actual label name