swift - UITableView didSelectRow 返回错误的行索引值
问题描述
当我选择一行时,它会返回一个更大或更小的行索引值,但绝不会是正确的值。如图所示,我选择 14 返回 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)
}
我该怎么做才能获得正确的行索引?谢谢!
解决方案
检查您的代表姓名是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)
}
根据您的代码,我创建了示例项目
推荐阅读
- dependency-injection - play 2.6.x 环境依赖注入
- android - 如何以 xamarin 形式使用系统时钟/时间?
- java - 春季启动火花应用
- python - Google Pubsub 推送到 AppEngine 502 和 504 错误
- javascript - 代理数组有一个与方法名同名的键
- amazon-web-services - 端口 80 和 443 关闭
- shell - 使用 awk 在输出中添加自定义列
- python - 尝试将 json 文件加载到扁平化的 pandas DataFrame 中
- bluez - 使用随机地址设置 BlueZ GATT 服务器?
- django - django 对值或函数值求和