在TableView中选择单元格时获取标签文本(Swift)

问题描述 投票:0回答:2

我有以下代码,我想打印所选单元格的文本(一个带有文本标签的自定义单元格)。

    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
    }




}

我已经尝试在didSelect row中添加以下代码,但得到的结果是nil。

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

我有什么办法可以做到这一点?

ios swift tableview selected
2个回答
1
投票

从原始源头获取...

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

1
投票

由于你是从数据源中设置文本,所以当单元格被选中时,你可以检查数据源中的索引

if let text = objectsArray[indexPath.section].sectionObjects[indexPath.row]{
//Do Something
}
© www.soinside.com 2019 - 2024. All rights reserved.