【发布时间】:2016-09-14 12:57:31
【问题描述】:
我有一个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
}
知道如何始终一次只选择一个单元格吗?
谢谢!
【问题讨论】:
-
你需要使用 DIDSELECT 而不是 WILL SELECT 并且在方法中你已经有了 indexpath 为什么你要做像 tableView.indexPathForSelectedRow 这样的代码
-
@NitinGohel 使用上面的代码,即使我将其更改为使用 didSelectRow 我仍然观察到相同的行为
-
让我发布一个答案,给我一些薄荷糖
标签: ios swift uitableview