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

标签 ios swift uitableview

我有一个 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/

相关文章:

ios - 编辑器中缺少 Xcode 文件

c++ - std::vector<T>::resize 等价于 swift

ios - 在 Xcode 中重新调整坐标系

ios - cellForRowAtIndexPath 单元测试崩溃

ios - 以编程方式从 UITableViewController 将 UIImage 设置为 UITableView 的背景

ios - 以编程方式检测来自 UI 元素的事件

iphone - 在以下示例中如何从 NSSArray 元素获取值?

ios - iOS 中 UITableViewCell 中的 UITableView

ios - 如何调整我的约束,以便仅当用户滚动 UITableView 时才显示我的 UITextView?

ios - 在自定义动画过渡期间淡入背景 View