2012-04-09 3 views
19

Sto usando un file di layout NIB una cella di vista tabella personalizzata. Questa cella ha un'etichetta con uscita chiamata lblName. L'aggiunta di un UITapGestureRecognizer a questa etichetta non genera mai l'evento associato. Ho userInteractionEnabled = YES.Come posso aggiungere un'UITapGestureRecognizer ad un UILabel all'interno di una cella di visualizzazione della tabella?

Sto indovinando che il problema è che l'UILabel è in una TableView e che la vista tabella/cella sta intercettando i rubinetti. Posso fare qualcosa a riguardo?

Tutto quello che voglio fare è eseguire alcune azioni personalizzata quando si preme un UILabel! Tutte le soluzioni per fare ciò che ho visto sono ridicole. Dovrebbe essere facile usando il set di strumenti standard. Ma evidentemente no.

Ecco il codice che sto utilizzando:

- (void)tapAction { 
    NSLog(@"Tap action"); 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib 

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
    [recognizer setNumberOfTapsRequired:1]; 
    //lblName.userInteractionEnabled = true; (setting this in Interface Builder) 
    [lblName addGestureRecognizer:recognizer]; 
} 

risposta

20

EASY WAY :

Si può anche utilizzare un invisibile b utton in cima a quell'etichetta. Quindi ridurrà il tuo lavoro di aggiungere tapGesture per quell'etichetta.

modo alternativo:

Non si dovrebbe creare un IBOutlet per quella UILabel. Quando lo fai, aggiungi un punto vendita nel file di implementazione della classe personalizzata. Non è possibile accedere in altro file. Quindi impostare un tag per quell'etichetta in classe personalizzata IB e scrivere un codice in cellForRowAtIndexPath: metodo.

aggiornamento:

In cellForRowAtIndexPath: metodo,

for(UIView *view in cell.contentViews.subviews) { 
    if(view.tag == 1) { 
     UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
     [tap setNumberOfTapsRequired:1]; 
     [view addGestureRecognizer:tap]; 
    } 
} 
+0

Grazie , questo ha fatto il trucco! Risolvi un paio di refusi nel tuo codice: prima "se" dovrebbe essere un "for" ovviamente e poi vuoi enumerare cell.contentViews.subviews. Grazie per la risposta! – Bryan

+0

Oh, mi sono iscritto qui. Ci sono piccoli errori. In ogni caso lo aggiornerò. –

+3

Questo non ha funzionato per me finché non ho impostato "Interazione utente abilitata" sulla cella stessa –

9

Facendo questo funziona senza problemi:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    ... 
    // create you cell 
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)]; 
    [lbl setText:@"example"]; 
    [lbl setUserInteractionEnabled:YES]; 
    [cell.contentView addSubview:lbl]; 
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; 
    tap.tag = [NSIndexPath row]; 
    [tap setNumberOfTapsRequired:1]; 
    [lbl addGestureRecognizer:tap]; 
    ... 
} 

- (void)tapAction:(id)sender { 
    switch(((UITapGestureRecognizer *)sender).view.tag) { 
    case 0: 
      // code 
      break; 
    case 1: 
     // code 
     break; 
     .... 
    } 
} 

anche nel caso in cui crea l'UILabel con IB

+0

Questo lo aiuterà. Ma ha bisogno di creare un'etichetta all'interno di UITableViewCell con il gesto Tap. –

+0

quindi nel metodo di creazione delle celle, quando crei un UITapGestureRecognizer, dagli un tag e gestisci l'evento nel gestore per differenziare il tag. – WhiteTiger

+0

Potresti semplicemente spiegare in un codice ?? –

0

Il modo Dinesh suggerito funzionerà senza il ciclo for usando la variabile di proprietà.

UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
[tap setNumberOfTapsRequired:1]; 
[self.myUILabel addGestureRecognizer:tap]; 
12
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
[recognizer setNumberOfTapsRequired:1]; 
lblName.userInteractionEnabled = YES; 
[lblName addGestureRecognizer:recognizer]; 
+1

È necessario impostare userInteractionEnabledProperty su YES. Nel mio caso, l'etichetta era all'interno di un'altra vista, e senza questo il gesto non ha funzionato. – alcamla

0

È possibile aggiungere successiva metodo

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizerAction:)]; 
[self.yourLabel setUserInteractionEnabled:YES]; 
[self.yourLabel addGestureRecognizer:gesture]; 
1

-awakeFromNib del tuo cellulare Dopo aver assegnato il gesto del rubinetto al UILabel e impostare l'interazione dell'utente per abilitato, nella funzione di callback è possibile trova il percorso dell'indice dalla vista cella ma cerca attraverso il nido di interviste:

- (UITableViewCell *) findCellInSuperview:(UIView *)view 
{ 
UITableViewCell *cell = nil; 

    NSString *className = NSStringFromClass([[view superview] class]); 
    if ([className isEqualToString:@"UITableViewCell"]) { 
     cell = (UITableViewCell *)[view superview]; 
    } else { 
     if ([view superview] != nil) { 
      cell = [self findCellInSuperview:[view superview]]; 
     } 
    } 

return cell; 
} 
0

Per Swift , puoi aggiungerlo nel tuo metodo cellForRowAtIndexPath.

var tap = UITapGestureRecognizer(target: self, action: "labelTapped") 
tap.numberOfTapsRequired = 1 
cell.label.addGestureRecognizer(tap) 
cell.label.tag = indexPath.row 

Poi per l'azione

func labelTapped(gesture: UITapGestureRecognizer) { 
    let indexPath = NSIndexPath(forRow: gesture.view!.tag, inSection: 0) 
    let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell 

    // Do whatever you want. 
} 
+1

L'OP ha fatto una domanda su Objective-C, non su Swift. –

+1

Quello che hai causerà un errore di runtime. 'action:" labelTapped "' sta dicendo che il metodo si aspetta di essere chiamato senza parametri ma la firma del metodo suggerisce diversamente. – maml

+0

Le celle di visualizzazione tabella sono ** riutilizzate **; non c'è il rischio di aggiungere il gesture recognition più volte alla stessa cella? (la stessa domanda si applica a "addTarget: action: forControlEvents:" nei pulsanti contenuti all'interno delle celle). –

4

È possibile utilizzare sotto codice per aggiungere gesto rubinetto UILable nella cella UITableView

UITapGestureRecognizer *lblAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lblClick:)]; 
lblAction.delegate =self; 
lblAction.numberOfTapsRequired = 1; 
cell.lbl.userInteractionEnabled = YES; 
[cell.lbl addGestureRecognizer:lblAction]; 

e per accedere al metodo di selezione

- (void)lblClick:(UITapGestureRecognizer *)tapGesture { 
    UILabel *label = (UILabel *)tapGesture.view; 
    NSLog(@"Lable tag is ::%ld",(long)label.tag); 
} 

Per Swift

let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(lblClick(tapGesture:))) 
tapGesture.delegate = self 
tapGesture.numberOfTapsRequired = 1 
cell.lbl.userInteractionEnabled = true 
cell.lbl.tag = indexPath.row 
cell.lbl.addGestureRecognizer(tapGesture) 

func lblClick(tapGesture:UITapGestureRecognizer){ 
    print("Lable tag is:\(tapGesture.view!.tag)") 
} 
0

Per Swift 3

let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: 
#selector(lblClick(tapGesture:))) 
tapGesture.delegate = self 
tapGesture.numberOfTapsRequired = 1 
cell.lbl.isUserInteractionEnabled = true 
cell.lbl.tag = indexPath.row 
cell.lbl.addGestureRecognizer(tapGesture) 

E poi

func lblClick(tapGesture:UITapGestureRecognizer){ 
    print("Lable tag is:\(tapGesture.view!.tag)") 
}