82

I'm trying to get index of selected item in TableView and start some activity after that. Unfortunately most of solutions that I found are in objective-c or do not work.

Method func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) don't print the cell label..

Can somebody help me please?

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDataSource {
    
    let tasks=[("Short walk"),
        ("Audiometry"),
        ("Finger tapping"),
        ("Reaction time"),
        ("Spatial span memory")
    ]
    
    
    //how many sections are in your table
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    //return int how many rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }
    
    //what are the contents
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        
        var (testName) = tasks[indexPath.row]
        cell.textLabel?.text=testName
        return cell
    }
    
    // give each table section a name
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return "Tasks"
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let indexPath = tableView.indexPathForSelectedRow();
        
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
        
        println(currentCell.textLabel!.text)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }  
}

After a few tries I changed the code to a different one from tutorial that I found. And it doesn't work too. Now I'm thinking this is the issue with iOS simulator...

import UIKit
import ResearchKit

class TaskListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet
    var tableView: UITableView?
    var items: [String] = ["We", "Heart", "Swift"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
        
        cell.textLabel?.text = self.items[indexPath.row]
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(items[indexPath.row])!")
    }
    
}

user745587
  • 125
  • 1
  • 12
pawisoon
  • 1,427
  • 1
  • 15
  • 20

9 Answers9

88

If you want the value from cell then you don't have to recreate cell in the didSelectRowAtIndexPath

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

Task would be as follows :

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

also you have to check the cellForRowAtIndexPath you have to set identifier.

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
}

Hope it helps.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
45

In Swift 3.0

You can find the event for the touch/click of the cell of tableview through it delegate method. As well, can find the section and row value of the cell like this.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       print("section: \(indexPath.section)")
       print("row: \(indexPath.row)")
}
ukw
  • 166
  • 2
  • 14
jaiswal Rajan
  • 4,641
  • 1
  • 27
  • 16
16

A of couple things that need to happen...

  1. The view controller needs to extend the type UITableViewDelegate

  2. The view controller needs to include the didSelectRowAt function.

  3. The table view must have the view controller assigned as its delegate.


Below is one place where assigning the delegate could take place (within the view controller).

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

And a simple implementation of the didSelectRowAt function.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
11

Problem was solved by myself using tutorial of weheartswift

enter image description here

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
pawisoon
  • 1,427
  • 1
  • 15
  • 20
  • 6
    Does the selected answer actually fix the issue? If it does not fix the issue, please write a solution onto your answer or select the appropriate answer to fix the question you asked. Just because someone offers help and a possible solution, doesn't mean their answer should be selected as the correct one. Please fix this. – Devbot10 Jan 16 '17 at 06:44
8

This worked good for me:

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

The output should be:

section: 0
row: 0
Gautam Savaliya
  • 1,403
  • 2
  • 20
  • 31
Mr Duck
  • 115
  • 1
  • 9
  • 6
    Your answer appears duplicate, as this Answer appears very similar to the above Answer https://stackoverflow.com/a/41583381/40867 – jdev Jul 21 '17 at 02:48
7

Inherit the tableview delegate and datasource. Implement delegates what you need.

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

And Finally implement this delegate

     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }
Pankaj Jangid
  • 812
  • 9
  • 18
4

To get an elements from Array in tableView cell touched or clicked in 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)")
}
Sanjay Mali
  • 506
  • 6
  • 13
3
 # 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)")
    }
Prabhat Pandey
  • 277
  • 10
  • 13
2

I screw up on the every time! Just make sure the tableView delegate and dataSource are declared in viewDidLoad. Then I normally populate a few arrays to simulate returned data and then take it from there!

//******** 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!
}
Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
Lexter
  • 33
  • 8