UITableView didSelectRow返回错误的行索引值

时间:2018-06-21 08:08:50

标签: swift uitableview

当我选择一行时,它将返回更大或更小的行索引值,但永远不会返回正确的值。如图所示,我选择了14返回16。

selected 14 returned 16

这是我使用的代码:

  @IBOutlet var cheatTable: UITableView!

  let cheetSheet = ["one", "two", "three", "four", "five"]
  override func viewDidLoad() {
    super.viewDidLoad()
    cheatTable.delegate = self
    cheatTable.dataSource = self
  }

  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 30
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseID")!
    let text:String = "\(indexPath.row)"
    cell.textLabel?.text = text
    return cell
  }

  func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    guard let currentCell = tableView.cellForRow(at: indexPath) else {
      return
    }
    let alertController = UIAlertController(title: "Hint", message: "You have selected row \(indexPath.row).", preferredStyle: .alert)
    let alertAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
    alertController.addAction(alertAction)
    present(alertController, animated: true, completion: nil)
  }

我该怎么做才能获得正确的行索引? 谢谢!

1 个答案:

答案 0 :(得分:9)

检查您的代表姓名不是 didDeselectRowAt ,它是 didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)


    let alertController = UIAlertController(title: "Hint", message: "You have selected row \(indexPath.row).", preferredStyle: .alert)
    let alertAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
    alertController.addAction(alertAction)
    present(alertController, animated: true, completion: nil)
}

按照您的代码,我创建了sample project