2014-10-30 6 views
8

Sto creando un'app utilizzando Swift. Ho un UITableView che compilo con alcuni dati da un database. Quando l'utente fa clic su una cella, vorrei attivare un'azione.Attiva un'azione quando un utente fa clic su una cella in rapido

quello che ho fatto:

var array: [String] = ["example"] 


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array.count 
    } 



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell = UITableViewCell(style :UITableViewCellStyle.Default, reuseIdentifier: "cell") 
     cell.textLabel.text = array[indexPath.row] 
     cell.tag = indexPath.row 
     cell.targetForAction("getAction:", withSender: self) 
     return cell 
    } 

    func getAction(sender:UITableViewCell)->Void { 
     if(sender.tag == 0) { 
      println("it worked") 
     } 
    } 

ho cercato di adattare una soluzione da un altro post, ma l'ho fatto sicuramente sbagliato. Grazie in anticipo

risposta

17

Implementare UITableViewDelegate e utilizzare didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 

è possibile utilizzare il indexPath per ottenere l'oggetto dalla tua collezione ed effettuare la vostra azione

+1

Grazie, è perferct! – soling

+1

non dimenticare di implementare il protocollo 'UITableViewDelegate' per ottenere il metodo' didSelectRowAtIndexPath' – LynAs

4

a Swift 4, credo che il metodo è cambiato mai così poco:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    // your code 
} 
Problemi correlati