UITableView didSelectRowAtIndexPath get instance of selected



有没有办法获取选择行的部分的实例?可以获取部分的索引,所选单元格的索引,所选单元格的实例。但是本节的实例呢?

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
}

谢谢。

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

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

使用函数 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
}

或 Swift 3.0,使用

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

/

/你的代码...

}

最新更新