gpt4 book ai didi

ios - 尽管我以编程方式选择了一个单元格,但 indexPathForSelectedRow 返回 nil

转载 作者:行者123 更新时间:2023-11-30 13:05:02 26 4
gpt4 key购买 nike

我有一个 UITableView,我加载了一些应用程序设置。我需要单选表格,并且由于表格保存设置,因此可能有机会根据设置启用状态以编程方式选择某些单元格。

目前,我遇到了一种奇怪的行为,如果我以编程方式选择一个单元格,那么 indexPathForSelectedRow 返回 nil (当它应该返回我选择的单元格的索引时) ,因此,当我点击第二个单元格(以更改当前选定的设置)时,我最终会选择两个单元格(即使我在 tableView 对象中将 allowMultipleSelection 设置为 false)。

这是我的代码:

override func viewDidLoad() {
tableView.allowsMultipleSelection = false
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("myCell")

if let cell = cell {
// tableObject is an array containing settings model
let row = tableObject[indexPath.row]
cell.textLabel!.text = row.settingValue
if row.selected {
cell.setSelected(true, animated: false)
cell.accessoryType = .Checkmark
}
cell.tag = row.id
}

return cell!
}

override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
// oldIndex is always nil for the cell I called setSelected in cellForRowAtIndexPath
if let oldIndex = tableView.indexPathForSelectedRow {
if let oldCell = tableView.cellForRowAtIndexPath(oldIndex) {
tableView.deselectRowAtIndexPath(oldIndex, animated: true)
oldCell.accessoryType = .None
}
}

if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.setSelected(true, animated: true)
cell.accessoryType = .Checkmark
}

return indexPath
}

override func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
return indexPath
}

知道如何才能每次只选择一个单元格吗?

谢谢!

最佳答案

以防万一其他人遇到同样的行为,似乎通过 cell.setSelected() 选择单元格与调用 tableView.selectRowAtIndexPath() 不同> 方法。选择最新的行可以完美地完成工作并解决问题。

关于ios - 尽管我以编程方式选择了一个单元格,但 indexPathForSelectedRow 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39491045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com