多选UITableView,不带dequeueReusableCellWithIdentifier

时间:2016-12-21 23:35:32

标签: ios swift uitableview

在我的tabeview中选择多个单元格时,也会选择不在视图中的单元格。我明白这是因为我正在重复使用单元格,并在向下滚动时保持其选择。我找到了一些有类似问题的人,但无法翻译他们的解决方案以解决我的问题。我已经尝试不对单元格进行出列,只需使用:

 let cell = NewBillSplitterItemCell() 

但得到:

 unexpectedly found nil while unwrapping an Optional value

就行:

cell.currentSplitters.text = splitterList

在以下代码中:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        fetchBillItems()

        let cell: NewBillSplitterItemCell = tableView.dequeueReusableCellWithIdentifier("NewBillSplitterItemCell") as! NewBillSplitterItemCell
        let item = allItems[indexPath.row]
        let numberOfSplitters = item.billSplitters?.count

        if numberOfSplitters == 0 {
            cell.currentSplitters.text = "No one is paying for this item yet."
        } else {

            var splitterList = "Split this item with "
            let itemSplitters = item.billSplitters?.allObjects as! [BillSplitter]
            for i in 0...Int((numberOfSplitters)!-1) {
                if numberOfSplitters == 1 {
                    splitterList += "\(itemSplitters[i].name!)"
                } else {
                    splitterList += ", \(itemSplitters[i].name!)"
                }
            }
            cell.currentSplitters.text = splitterList
        }

        cell.name.text = item.name
        cell.price.text = "£\(item.price!)"

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark
            {
                cell.accessoryType = .None
                selectedItems.removeAtIndex(selectedItems.indexOf(allItems[indexPath.row])!)
            } else {
                cell.accessoryType = .Checkmark
                selectedItems.append(allItems[indexPath.row])
            }
        }
    }

我不太明白该怎么做,任何帮助都会很棒。感谢

2 个答案:

答案 0 :(得分:2)

除了@Mike所说的内容之外,cellForRowAtIndexPath内部需要额外检查,因为单元格会被重用。

沿线的东西

let isSelected = selectedItems[indexPath.row].selected
if isSelected{
    cell.accessoryType = .Checkmark
} else {
    cell.accessoryType = .None
}

didSelectRowAtIndexPath内部,您应更新数据源,而不是依赖于您的单元格的UI

答案 1 :(得分:1)

假设小区 nil ,您应该使用

let cell = tableView.dequeueReusableCellWithIdentifier("..." forIndexPath:indexPath) as! NewBillSplitterItemCell

而不是

let cell= tableView.dequeueReusableCellWithIdentifier("...") as! NewBillSplitterItemCell

这确保了单元格永远不会为零。

另外,我会检查所有.xib .storyboard文件中是否使用了正确的标识符