在 Swift 的 Tableview 中禁用多行选择
Posted
技术标签:
【中文标题】在 Swift 的 Tableview 中禁用多行选择【英文标题】:Disabling Mutliple Row Selection in Tableview in Swift 【发布时间】:2017-02-07 11:52:09 【问题描述】:我是 Swift 新手,我想在我的表格视图中禁用多行选择。我尝试实现不同类型的方法,我的最终代码块如下,这是行不通的。 感谢您的帮助。
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
【问题讨论】:
allowsMultipleSelection = false
工作正常。
默认情况下,单选仅在情节提要中被选中。在情节提要中-> 选择您的表格视图,在属性检查器下有一个选择选项:否、单选、多选。如果您不想在运行时更改它,可以从情节提要中进行设置。 allowsMultipleSelection
的默认值也是 false。
显示cellForRowAtindexPath
代码。
Priyal,我已经在 Storyboard 中选择了“单选”,但它并没有解决我的问题。
【参考方案1】:
请试试这个代码:
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
【讨论】:
嗨波兰人,我已经在 Storyboard 中选择了“单选”,但它并没有解决我的问题。 那么我认为问题出在代码didSelectRowAt
部分。您的单选工作正常,但您设置复选标记的方式有问题。【参考方案2】:
您的选择/取消选择调用似乎有问题。使用这样的东西: 这里我有一个 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
【讨论】:
以上是关于在 Swift 的 Tableview 中禁用多行选择的主要内容,如果未能解决你的问题,请参考以下文章
无法在 Alamofire 中禁用缓存(Xcode 9 - swift 4)