【发布时间】:2015-09-27 16:44:29
【问题描述】:
我有一个包含人员列表的 tableView。我想选择多个单元格。我创建了一个字典来存储选定的单元格 (screenshot)。
var checkedSubjects: [Person: Bool] = [Person: Bool]()
然后,当我选择一个单元格时,它会在该单元格附近显示一个复选标记并将其保存在我的数组中 (screenshot)。
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)
}
}
但是当我再按一次这个单元格时,我希望它返回到默认视图。它会删除复选标记,但文本不会占用空格 (screenshot)。标签的尾随约束设置为容器边距。
我已经尝试在 didSelectRowAtIndexPath 中 reloadData() 的 tableView 但它没有帮助。
有什么办法可以解决这个问题吗?
【问题讨论】:
-
@matt 谢谢你,我按照你的回答,现在效果很好!)
-
请将其发布为答案并将其标记为已接受适当的内务管理。
-
@matt 它帮助了我,就这样吧)。
-
好的,这样做了,并删除了我的 cmets。
标签: ios swift didselectrowatindexpath tableviewcell accessoryview