Search code examples
iosswifttableviewselected

Getting label text when Cell is Selected in TableView (Swift)


I have the below code and I want to print the text of the selected cell ( a custom cell with a text label )

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "DateCell", for: indexPath) as! DateCell

    cell.dateLabel.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]
    cell.selectionStyle = .none
    contentView.separatorStyle = .singleLine
    contentView.allowsSelection = true

    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    if contentView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.none{
        contentView.cellForRow(at: indexPath)?.accessoryType = .checkmark


    }
    else{
        contentView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }




}

I already tried adding the below code in didSelect row at but I get nil.

print ((contentView.cellForRow(at: indexPath)?.textLabel?.text)!)

Any ideas on how I can do this?


Solution

  • Get it from the original source...

    func tableView(_ tableView: UITableView, 
                   didSelectRowAt indexPath: IndexPath) {
        let str = objectsArray[indexPath.section].sectionObjects[indexPath.row]
        print(str)
    }