我有一个UITableView
我加载了一些应用程序设置。我需要表格是单选的,并且由于表格保存了设置,因此可能有一些单元格会根据设置启用状态以编程方式选择。indexPathForSelectedRow返回零,但我有一个单元格编程选择
目前,我遇到一个奇怪的行为,其中,如果以编程方式选择一个单元格,然后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不将选择和方法,你已经有了indexpath你为什么不喜欢tableView.indexPathForSelectedRow –
@NitinGohel代码带上面的代码甚至当我改变它使用didSelectRow我仍然观察到相同的行为 – mradzinski
让我发表一个答案给我几个薄荷 –