[英]Disabling Mutliple Row Selection in Tableview in Swift
我是Swift的新手,我想在tableview中禁用多行選擇。 我嘗試實現不同類型的方法,並且下面的最終代碼塊不起作用。 謝謝你的幫助。
override func viewDidLoad() {
super.viewDidLoad()
companyTableView.allowsMultipleSelection = false
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark;
}
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) {
if selectedCells.contains(indexPath.row) {
selectedCells.remove(indexPath.row)
cell.accessoryType = .none
} else {
selectedCells.insert(indexPath.row)
cell.accessoryType = .checkmark
}
}
}
請嘗試以下代碼:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if !selectedCells.contains(indexPath){
selectedCells.add(indexPath)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if selectedCells.contains(indexPath){
selectedCells.remove(indexPath)
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
}
在cellForRowAt
使用以下代碼:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedCells.contains(indexPath){
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
return cell
}
您的選擇/取消選擇通話中似乎存在問題。 使用類似這樣的東西:在這里,我有一個selectedCells數組(其大小等於單元格總數的數量)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
if filteredStudents.count > indexPath.row {
selectedCells[indexPath.row] = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
if selectedStudents.count > indexPath.row {
selectedCells[indexPath.row] = false
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.