我有一个 tableView,它有两个不同的部分,一个用于单选,另一个用于多选。我还为此构建了两个不同的自定义单元格。我能够正确选择多选,但不能正确选择单选。
我正在使用由 tableView Cell 提供的覆盖 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
有人可以帮我解决这个问题吗?
最佳答案
要执行您想要的操作,您需要保持单元格的选择状态,对于单选部分,声明一个类型为 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)
}
}
关于ios - 同一 TableView 中的单选和多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337657/