web-dev-qa-db-fra.com

Comment détecter la cellule tableView touchée ou cliquée rapidement

J'essaie d'obtenir index de l'élément sélectionné dans TableView et de commencer une activité par la suite. Malheureusement, la plupart des solutions que j'ai trouvées sont en Objective-C ou ne fonctionnent pas.

Méthode func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) N'imprimez pas l'étiquette cell.

Quelqu'un peut m'aider s'il vous plait?

 import UIKit 
 import ResearchKit 

 class TaskListViewController: UIViewController, UITableViewDataSource {

 laisser tâches = [("courte marche"), 
 ("Audiométrie"), 
 ("Taper sur les doigts"), 
 ("Temps de réaction"),
 ("Mémoire spatiale étendue") 
 ] 


 // combien de sections sont dans votre table 
 func numberOfSectionsInTableView (tableView: UITableView) -> Int {
 retourne 1 
 } 

 // retourne int combien de lignes 
 func tableView (tableView: UITableView, section numberOfRowsInSection: Int) -> Int {
 renvoyer tâches.count 
 } 

 // quels sont les contenus 

 func tableView (tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 var cell = UITableViewCell () 

 var (testName) = tâches [indexPath.row] 
 cell.textLabel? .text = testName 
 cellule de retour 
 } 

 // donne un nom à chaque section de la table 

 func tableView (tableView: UITableView, section titleForHeaderInSection: Int) -> Chaîne? {

 retournez "Tasks" 

 } 

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

 let indexPath = tableView.indexPathForSelectedRow (); 

 let currentCell = tableView.cellForRowAtIndexPath (indexPath!) comme UITableViewCell! .________. println (currentCell.textLabel! .text) 
 } 


 redéfinit func viewDidLoad () {
 super.viewDidLoad () 

 } 
} 

Après quelques essais, j'ai remplacé le code par un code différent de celui trouvé. Et ça ne marche pas aussi. Maintenant, je pense que c'est le problème avec le simulateur iOS ...

 import UIKit 
 import ResearchKit 

 class TaskListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 @IBOutlet 
 var tableView: UITableView? 
 var items: [String] = ["Nous", "Coeur", "Rapide"] 

 redéfinit func viewDidLoad () {
 super.viewDidLoad () 

 self.tableView! .registerClass (UITableViewCell.self, forCellReuseIdentifier: "cellule") 
 } 


 func tableView (tableView: UITableView, section numberOfRowsInSection: Int) -> Int {
 retourne self.items.count; 
 } 

 func tableView (tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 var cellule: UITableViewCell = self.tableView! .dequeueReusableCellWithIdentifier ("cellule") en tant que! UITableViewCell 

 cell.textLabel? .text = self.items [indexPath.row] 

 cellule de retour 
 } 

 func tableView (tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
 println ("Vous avez sélectionné la cellule #\(items [indexPath.row])!") 
 } 

} 

44
pawisoon

Si vous voulez la valeur de la cellule, vous n'avez pas à recréer la cellule dans la variable didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(tasks[indexPath.row])
}

La tâche serait la suivante:

let tasks=["Short walk",
    "Audiometry",
    "Finger tapping",
    "Reaction time",
    "Spatial span memory"
]

vous devez également vérifier la cellForRowAtIndexPath que vous devez définir identifiant. 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    var (testName) = tasks[indexPath.row]
    cell.textLabel?.text=testName
    return cell
}

J'espère que ça aide.

47
Ashish Kakkad

Dans Swift 3.0

Vous pouvez trouver l'événement pour le contact/clic de la cellule de table avec la méthode déléguée. De même, vous pouvez trouver la valeur de section et de ligne de la cellule comme ceci.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}
26
jaiswal Rajan

Quelques choses qui doivent arriver ...

  1. Le contrôleur de vue doit étendre le type UITableViewDelegate

  2. Le contrôleur de vue doit inclure la fonction didSelectRowAt.

  3. Le contrôleur de vue doit être attribué à la vue de la table en tant que son délégué.


Ci-dessous se trouve un endroit où l'attribution du délégué pourrait avoir lieu (dans le contrôleur de vue).

override func loadView() {
    tableView.dataSource = self
    tableView.delegate = self
    view = tableView
}

Et une implémentation simple de la fonction didSelectRowAt.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}
6
spencer.sm

Cela a bien fonctionné pour moi:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

Le résultat devrait être:

section: 0
row: 0
5
Mr Duck

Le problème a été résolu par moi-même en utilisant le didacticiel de weheartswift

 enter image description here

4
pawisoon

Hériter du délégué tableview et de la source de données . Implémentez les délégués dont vous avez besoin.

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

Et enfin implémenter ce délégué

     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }
3
Pankaj Jangid
 # Check delegate? first must be connected owner of view controller

    # Simple implementation of the didSelectRowAt function.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         print("row selection: \(indexPath.row)")
    }
2
Prabhat Pandey

Pour obtenir un élément de Array dans une cellule de la table de tableau touché ou cliqué dans Swift

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text= arr_AsianCountries[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexpath = arr_AsianCountries[indexPath.row]
print("indexpath:\(indexpath)")
}
2
Sanjay Mali

Je bousille à chaque fois! Assurez-vous simplement que le délégué tableView et la source de données sont déclarés dans viewDidLoad. Ensuite, je renseigne normalement quelques tableaux pour simuler les données renvoyées, puis les récupérer à partir de là!

//******** Populate Table with data ***********
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SetupCellView
    cell?.ControllerLbl.text = ViewContHeading[indexPath.row]
    cell?.DetailLbl.text = ViewContDetail[indexPath.row]
    cell?.StartupImageImg.image = UIImage(named: ViewContImages[indexPath.row])
    return cell!
}
0
Lexter