tap gesture recognizer - ¿qué objeto se tocó?
Soy nuevo en los reconocedores de gestos, así que tal vez esta pregunta suene tonta: Estoy asignando reconocedores de gestos tap a un montón de UIViews. En el método ¿es posible averiguar cuál de ellos fue aprovechado de alguna manera o necesito averiguarlo usando el punto que fue aprovechado en la pantalla?
for (NSUInteger i=0; i<42; i++) {
float xMultiplier=(i)%6;
float yMultiplier= (i)/6;
float xPos=xMultiplier*imageWidth;
float yPos=1+UA_TOP_WHITE+UA_TOP_BAR_HEIGHT+yMultiplier*imageHeight;
UIView *greyRect=[[UIView alloc]initWithFrame:CGRectMake(xPos, yPos, imageWidth, imageHeight)];
[greyRect setBackgroundColor:UA_NAV_CTRL_COLOR];
greyRect.layer.borderColor=[UA_NAV_BAR_COLOR CGColor];
greyRect.layer.borderWidth=1.0f;
greyRect.userInteractionEnabled=YES;
[greyGridArray addObject:greyRect];
[self.view addSubview:greyRect];
NSLog(@"greyGrid: %i: %@", i, greyRect);
//make them touchable
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter)];
letterTapRecognizer.numberOfTapsRequired = 1;
[greyRect addGestureRecognizer:letterTapRecognizer];
}
10 answers
Defina su selector de destino (highlightLetter:
) con el argumento como
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
Entonces usted puede obtener vista por
- (void)highlightLetter:(UITapGestureRecognizer*)sender {
UIView *view = sender.view;
NSLog(@"%d", view.tag);//By tag, you can find out where you had tapped.
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 11:26:46
Ha pasado un año haciendo esta pregunta, pero todavía para alguien.
Mientras se declara el UITapGestureRecognizer
en una vista particular, asigne la etiqueta como
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandlerMethod:)];
[yourGestureEnableView addGestureRecognizer:tapRecognizer];
yourGestureEnableView.tag=2;
Y en su controlador hacer así
-(void)gestureHandlerMethod:(UITapGestureRecognizer*)sender {
{
if(sender.view.tag==2) {
//do something here
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-09 10:03:24
Aquí hay una actualización para Swift 3 y una adición a la respuesta de Mani. Yo sugeriría usar sender.view
en combinación con etiquetar UIViews (u otros elementos, dependiendo de lo que esté tratando de rastrear) para un enfoque algo más "avanzado".
- Añadiendo el UITapGestureRecognizer a, por ejemplo, un UIButton (puede agregar esto a UIViews, etc. también) O un montón de elementos en una matriz con un bucle for y una segunda matriz para el grifo gesto.
let yourTapEvent = UITapGestureRecognizer(target: self, action: #selector(yourController.yourFunction))
yourObject.addGestureRecognizer(yourTapEvent) // adding the gesture to your object
-
Definir la función en el mismo TestController (ese es el nombre de su Controlador de vista). Vamos a usar etiquetas aquí - las etiquetas son ID Int, que puede agregar a su UIView con
yourButton.tag = 1
. Si tiene una lista dinámica de elementos como una matriz, puede crear un bucle for, que itera a través de su matriz y agrega una etiqueta, que aumenta de forma incrementalfunc yourFunction(_ sender: AnyObject) { let yourTag = sender.view!.tag // this is the tag of your gesture's object // do whatever you want from here :) e.g. if you have an array of buttons instead of just 1: for button in buttonsArray { if(button.tag == yourTag) { // do something with your button } } }
La razón de todo esto es porque no puedes pasar más allá argumentos para yourFunction cuando se usa junto con # selector.
Si tiene una estructura de interfaz de usuario aún más compleja y desea obtener la etiqueta de padre del elemento adjunto a su gesto de toque, puede usar let yourAdvancedTag = sender.view!.superview?.tag
por ejemplo, obtener la etiqueta de UIView de un botón presionado dentro de esa UIView; puede ser útil para listas de miniaturas+botones, etc.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-02 20:29:01
Utilice este código en 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
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-02 11:39:56
Puede usar
- (void)highlightLetter:(UITapGestureRecognizer*)sender {
UIView *view = sender.view;
NSLog(@"%d", view.tag);
}
View será el objeto en el que se reconoció el gesto tap
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 09:24:49
También puede usar el método "shouldReceiveTouch" de UIGestureRecognizer
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch: (UITouch *)touch {
UIView *view = touch.view;
NSLog(@"%d", view.tag);
}
No se olvide de establecer delegado de su recognizer gesto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-01 13:12:12
En swift es bastante simple
Escribe este código en la función viewDidLoad ()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler(gesture:)))
tap.numberOfTapsRequired = 2
tapView.addGestureRecognizer(tap)
La Parte del Manejador esto podría estar en viewDidLoad o fuera de viewDidLoad, la masa se pone en extensión
@objc func tapHandler(gesture: UITapGestureRecognizer) {
currentGestureStates.text = "Double Tap"
}
Aquí solo estoy probando el código imprimiendo la salida si quieres hacer una acción puedes hacer lo que quieras o más práctica y leer
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-02 06:05:07
Debe modificar la creación del reconocedor de gestos para aceptar el parámetro (agregue dos puntos':')
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
Y en su método highlightLetter: puede acceder a la vista adjunta a recogniser:
-(IBAction) highlightLetter:(UITapGestureRecognizer*)recognizer
{
UIView *view = [recognizer view];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 09:25:27
Si está agregando diferentes UIGestureRecognizer
en diferentes UIView
s y desea distinguir en el método de acción, puede verificar la vista de propiedades en el parámetro remitente que le dará la vista del remitente.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-07 12:31:29
func tabGesture_Call
{
let tapRec = UITapGestureRecognizer(target: self, action: "handleTap:")
tapRec.delegate = self
self.view.addGestureRecognizer(tapRec)
//where we want to gesture like: view, label etc
}
func handleTap(sender: UITapGestureRecognizer)
{
NSLog("Touch..");
//handling code
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-15 10:48:23