[英]How to convert multiple cell selection to single cell selection using Swift
In myscenario, I am trying to create single cell selection checkmark
at a time.在我的场景中,我试图一次创建单个单元格选择复选
checkmark
。 I used below code for multiple cell selection with isSelected
Bool value for selection cell persistent.我使用下面的代码进行多个单元格选择,并使用
isSelected
Bool 值来选择单元格持久化。 Now, how to convert below code for single cell selection
.现在,如何将以下代码转换为单个单元格
selection
。
My Code Below我的代码如下
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let item = self.titleData[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = item.isSelected ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
titleData[indexPath.row].isSelected.toggle()
tableView.reloadRows(at: [indexPath], with: .none)
let selectedTitle = titleData.filter{$0.isSelected}
print("\(selectedTitle)")
}
First, in viewDidLoad(), make your tableView to allow single selection only.首先,在 viewDidLoad() 中,让你的 tableView 只允许单选。 like this:
像这样:
yourTableView.allowsMultipleSelection = false
then you can use didSelectRowAt
and didDeselectRowAt
for this.那么您可以为此使用
didSelectRowAt
和didDeselectRowAt
。 This will enable only one selection at a time.这将一次只启用一个选择。
// assign isSelected true and accessoryType to checkmark
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
self.titleData[indexPath.row].isSelected = true
let selectedTitle = self.titleData[indexPath.row].title
cell.accessoryType = .checkmark
}
// assign isSelected false and accessoryType to none
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
self.titleData[indexPath.row].isSelected = false
cell.accessoryType = .none
}
You need to maintain global variable because if you want to manage using your array you need to reset isSelected bit of array every time before you do selection.您需要维护全局变量,因为如果您想使用数组进行管理,则需要在每次进行选择之前重置数组的 isSelected 位。
var isSelected = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let item = self.titleData[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = isSelected ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
isSelected = true
tableView.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.