www51
www51

Reputation: 60

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?

Upvotes: 0

Views: 709

Answers (2)

user13533653
user13533653

Reputation: 19

Since you are setting text from the data source, when cell is selected, you can check the index in your data source

if let text = objectsArray[indexPath.section].sectionObjects[indexPath.row]{
//Do Something
}

Upvotes: 1

Scriptable
Scriptable

Reputation: 19750

Get it from the original source...

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

Upvotes: 1

Related Questions