我有一个tableView,它有两个不同的部分,一个用于单个选择,另一个用于多个选择。我还为相同的单元格构建了两个不同的自定义单元。我可以得到多重选择的权利,但不是单一的选择。
对于单个选择和多个选择,我使用由setSelected单元提供的覆盖。
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
//make label red
}
} else {
//make label white
}
}但是,我面临的问题是,当我单击multipleSelection部分的单元格时,调用我的singleSelectionCell的setSelected ovveride并将标签标记为白色。如果已经在singleSelection中选择了一个单元格,我需要保持这种方式。
我看了这个答案,但我不知道该怎么做。https://stackoverflow.com/a/32857181/4863339
有人能帮我解决这个问题吗?
发布于 2017-02-20 09:19:21
要做您想做的事情,您需要维护单元格的选择状态,对于单个选择区段声明IndexPath?类型的一个实例属性,对于多个选择部分声明[IndexPath]类型的一个实例属性。然后比较了cellForRowAt方法中的这个属性,并在didSelectRowAt方法中改变了它的值。
编辑:使用自定义对象的您可以尝试这样做,使用您的sectionItem类创建一个类型为Bool的属性selected,并使用它来选择多个或单个项
所以你的课应该是这样的。
class Section {
var isMultiple: Bool
var title: String
var items: [Item]
init(isMultiple: Bool, title: String, items: [Item]) {
self.isMultiple = isMultiple
self.title = title
self.items = items
}
}
class Item {
var id: Int
var name: String
//To maintain selected state
var selected: Bool = false
init(id: Int, name: String) {
self.id = id
self.name = name
}
}现在,对于cellForRowAt和didSelectRowAt,它应该是这样的。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
let item = sections[indexPath.section].items[indexPath.row]
if sections[indexPath.section].isMultiple {
//For multiple selection
if item.selected {
cell.accessoryType = .checkmark //Or make label red
}
else {
cell.accessoryType = .none //Or make label white
}
}
else {
//For single selection
if item.selected {
cell.accessoryType = .checkmark //Or make label red
}
else {
cell.accessoryType = .none //Or make label white
}
}
cell.textLabel?.text = sections[indexPath.section].items[indexPath.row].name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if sections[indexPath.section].isMultiple {
//For multiple selection
let item = sections[indexPath.section].items[indexPath.row]
item.selected = !item.selected
sections[indexPath.section].items[indexPath.row] = item
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
else {
//For multiple selection
let items = sections[indexPath.section].items
if let selectedItemIndex = items.indices.first(where: { items[$0].selected }) {
sections[indexPath.section].items[selectedItemIndex].selected = false
if selectedItemIndex != indexPath.row {
sections[indexPath.section].items[indexPath.row].selected = true
}
}
else {
sections[indexPath.section].items[indexPath.row].selected = true
}
self.tableView.reloadSections([indexPath.section], with: .automatic)
}
}https://stackoverflow.com/questions/42337657
复制相似问题