繁体   English   中英

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

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

我有以下代码,我想打印所选单元格的文本(带有文本 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
    }




}

我已经尝试在 didSelect 行中添加以下代码,但我得到了 nil。

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

关于如何做到这一点的任何想法?

从原始来源获取它...

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

由于您正在从数据源设置文本,因此选择单元格时,您可以在数据源中检查索引

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM