ios - 如何在 tableview Swift 中获取选中标记的行列表?
问题描述
我启用了多行选择,并且能够在用户触摸特定单元格时添加复选标记。现在最后,我想查看哪些行被选择并根据行号执行操作。如何获取这些行详细信息/数字?谢谢!
用于选择/取消选择行的代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
main_table.reloadData()
self.main_table.allowsMultipleSelection = true
self.main_table.allowsMultipleSelectionDuringEditing = true
}
然后在单元控制器中:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? UITableViewCell.AccessoryType.checkmark : UITableViewCell.AccessoryType.none
}
解决方案
首先,避免使用下划线(_
)符号来声明Swift中的变量。而是使用驼色套管。
@IBOutlet weak var mainTable: UITableView!
接下来,要仅获取rows
中选定indexPaths
的tableView
,请使用indexPathsForSelectedRows
等map(_:)
,
if let selectedRows = self.tableView.indexPathsForSelectedRows?.map({ $0.row }) {
print(selectedRows)
}
由于indexPathsForSelectedRows
返回Optional
array
of IndexPath
,您需要将其解包以获取值。
推荐阅读
- function - is.na() 应用于“闭包”类型的非(列表或向量)
- facebook - 无法回拨 Facebook 点赞或分享
- python - 命令“python setup.py egg_info”在 C:\Users\USER\AppData\Local\Temp\pip-install-bmb0gfx2\jws\ 中失败,错误代码 1
- xml - cvc-complex-type.2.3:元素“项目”不能有子字符
- dependency-injection - 在 TopShelf 和 Quartz 范围问题中使用 Microsoft DependencyInjection
- javascript - 如何将第 3 方脚本集成到我的 html 代码中并将值传递给脚本?
- haskell - Type error when asigning tuple in do notation in haskell
- algorithm - 搜索中更好的数组或链表是什么?
- apache - Laravel Https 没有正确重定向
- meteor - Meteor:在模板中显示数据时出错