简体   繁体   English

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

[英]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 )我有以下代码,我想打印所选单元格的文本(带有文本 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.我已经尝试在 didSelect 行中添加以下代码,但我得到了 nil。

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

Any ideas on how I can do this?关于如何做到这一点的任何想法?

Get it from the original source...从原始来源获取它...

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

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
}

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

相关问题 迅速。选中后更改自定义Tableview单元格标签的颜色 - Swift. Change Color of Custom Tableview Cell Label when selected 在其他TableView控制器中将单元格文本选择时传输到uitextfield-Swift - Transfer cell text when selected to uitextfield in a different tableview controller - Swift 在swift中选择时,Tableview单元格返回nil - Tableview cell returns nil when selected in swift Swift - 选择 TableView 单元格时的动画 (didSelectRowAtIndexPath) - Swift - Animating When TableView Cell Selected (didSelectRowAtIndexPath) 选择单元格后,Swift tableView单元格子视图闪烁(消失,然后重新出现) - Swift tableView cell subviews flicker (disappear and then reappear) when cell is selected 单元格高度不增加取决于表格视图 swift 中的 label 文本 - Cell height is not increasing depend on the label text in tableview swift tableview 中的单元格不显示 Swift 中 label 的所有文本 - Cell in tableview don't show all the text of label in Swift Swift TableView传递所选单元格 - Swift TableView pass selected Cell 当其中的 label 文本被修改时,有没有办法改变 tableView 单元格的高度? - Is there a way to change tableView cell's height, when the label text in it is modified? 如何仅在TableView的选定单元格中显示标签? - How to display label only in the selected cell of a TableView?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM