我是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
}
}
}
答案 0 :(得分:0)
请尝试以下代码:
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
}
答案 1 :(得分:0)
您的选择/取消选择通话中似乎存在问题。使用这样的东西: 这里我有一个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
}
}