0

我有一个包含人员列表的 tableView。我想选择多个单元格。我创建了一个字典来存储选定的单元格(屏幕截图)。

var checkedSubjects: [Person: Bool] = [Person: Bool]()

然后,当我选择一个单元格时,它会在单元格附近显示一个复选标记并将其保存在我的数组中(屏幕截图)。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: SearchTableViewCell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as! SearchTableViewCell
    cell.tintColor = UIColor(hex: 0x3f51b5)
    cell.subjectNameLabel.text = subjects[indexPath.row].name
    cell.subjectDescriptionLabel.text = "(\(subjects[indexPath.row].type))"

    let person = Person(id: subjects[indexPath.row].id, name: subjects[indexPath.row].name, type: subjects[indexPath.row].type)
    if checkedSubjects[person] != nil {
        cell.accessoryType = checkedSubjects[person]! ? .Checkmark : .None
    }
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: false)
    let index = indexPath.row
    let person = Person(id: subjects[index].id, name: subjects[index].name, type: subjects[index].type)
    if tableView.cellForRowAtIndexPath(indexPath)!.accessoryType == .Checkmark {
        tableView.cellForRowAtIndexPath(indexPath)!.accessoryType = .None
        checkedSubjects[person] = false
        counter--
    } else {
        tableView.cellForRowAtIndexPath(indexPath)!.accessoryType = .Checkmark
        checkedSubjects[person] = true
        counter++
    }
    if counter > 0 {
        saveBtn.enabled = true
        let text = counter == 1 ? "Add \(counter) person" : "Add \(counter) persons"
        saveBtn.setTitle(text, forState: UIControlState.Normal)
    } else {
        saveBtn.enabled = false
        saveBtn.setTitle("Choose persons", forState: UIControlState.Normal)
    }
}

但是,当我再次按下此单元格时,我希望它返回默认视图。它会删除复选标记,但文本不会占用空格(屏幕截图)。标签的尾随约束设置为容器边距。

我已经尝试reloadData()在 didSelectRowAtIndexPath 中使用 tableView 但它没有帮助。

有什么想法可以解决这个问题吗?

4

1 回答 1

1

我认为这里的问题是你试图在你的didSelectRow实现中操纵物理单元。这是做事的错误方式。不要试图在你的didSelectRow实现中改变甚至读取单元格的附件类型!相反,完全在模型 ( checkedSubjects) 上操作并重新加载受影响的行,以便视图获取模型的更改(因为cellForRow将被调用)。

于 2015-09-27T17:45:13.993 回答