【问题标题】:UITableView didSelectRowAtIndexPath get instance of selected sectionUITableView didSelectRowAtIndexPath 获取所选部分的实例
【发布时间】:2016-06-22 05:16:43
【问题描述】:

有没有办法获取选择行的部分的实例?可以获取section的index,选中cell的index,选中cell的instance..但是这个section的instance呢?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let indexPath = tableView.indexPathForSelectedRow // index path of selected cell

    let headerCellIndex = indexPath!.section // index of selected section
    let headerCellName = ????? // instance of selected section

    let cellIndex = indexPath!.row // index of selected cell
    let cellName = tableView.cellForRowAtIndexPath(indexPath!) //  instance of selected cell
}

谢谢。

【问题讨论】:

  • tableview 加载时如何插入部分的名称?
  • String(content[section].sectionName) 这也适用于didSelectRowAtIndexPath-method..但是没有办法以某种方式获取节的名称,类似于获取所选单元格的名称?
  • 内容是数组/对象吗?
  • 在 didSelectRow 中你为什么不试试...var secName = content[indexPath.section].sectionName
  • 没有部分实例,您不应该从单元格中获取标签文本 - 始终从您的数据模型中获取数据,只获取单元格实例以便您可以更新它

标签: swift uitableview didselectrowatindexpath


【解决方案1】:

这对我来说一直很有效。我总是将它解包到我分配给它的类中,以确保我拥有正确类型的单元格。在这个例子中我有 MyTableViewCell 但它当然可以是任何东西。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   if let cell = tableView.cellForRow(at: indexPath) as? MyTableViewCell {
         print(cell.label.text!)
    }
}

【讨论】:

    【解决方案2】:

    使用 DidSelectRows 函数,您可以使用这样的开关(例如 3 个部分,可变行)

    switch indexPath.section {
    case 0:
       switch indexPath.row {
          case 0:
          Action to do with first cell (ex. performSegue(withIdentifier: "", sender: nil)
          case 1:
          Action to do with second cell
          default:
             break
          }
    case 1:
       Things you want to do in the second section
    case 2:
       Things you want to do in the third section
    default:
    break
    }
    

    【讨论】:

    • Sections 动态来自 Web 服务,如何获取 indexpath。
    【解决方案3】:

    或 Swift 3.0,使用

    覆盖 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: 索引路径){

    //你的代码...

    }

    【讨论】:

      猜你喜欢
      • 2014-04-14
      • 2022-01-12
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      相关资源
      最近更新 更多