ios - 在 UITableView 中至少选择一行
问题描述
嗨,有一个 UITableView 可以选择选中/取消选中每一行。它工作正常,不,我想确保至少选择了一行,并且当用户尝试取消选中时,向他显示必须选择至少一个选项的警报。我该如何实施?
这是当前代码
private var locationToDisplay = [Location]();
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource=self
self.tableView.delegate=self
self.tableView.allowsMultipleSelection = true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locationToDisplay.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SubscriptionCell", for: indexPath) as! SubscriptionTableViewCell
let cellLocation = locationToDisplay[indexPath.row]
cell.labelLocation.text = cellLocation.location_name
if cellLocation.subscribed == 1 {
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
} else {
self.tableView.deselectRow(at: indexPath, animated: false)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
locationToDisplay[indexPath.row].subscribed = 1
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if (countSelections()==1) {
//Last checked item
}
locationToDisplay[indexPath.row].subscribed = 0
}
func countSelections()->Int {
var count: Int = 0
for location in locationToDisplay {
if (location.subscribed == 1) {
count = count + 1
}
}
return count
}
解决方案
查看func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath?
委托方法。如果您不希望用户实际取消选择该行,您可以在此处返回 nil(然后您也可以显示警报)。
(此外,您不应该在方法中调用self.tableView.selectRow
或self.tableView.deselectRow
从cellForRowAt
方法中调用。请查看https://stackoverflow.com/a/13827975/403425以获得更多帮助。)
推荐阅读
- java - 如何从 Java 中保存在 C++ 中的字节数组中读取数字?
- python - 在 python 中,拥有一个可迭代对象和一个迭代器这两个单独的对象的目的是什么?
- phpstorm - 有没有办法在一个 PhpStorm 文件中使用多种语言?
- java - 我正在将一些 java 代码转换为 C。卡在一行 CharAt()
- c# - 为什么下面的代码输出 System.Int32 而不是 System.String?
- angular - Angular - 将外部 PDF 链接插入 iframe
- javascript - 如何将img元素的src属性切换回jquery?
- javascript - 如果满足条件,如何将项目设置为 Liquid 中 for 循环中的第一个项目
- python-3.x - 使用 os.write 打印字体图标
- c++ - 分段错误(核心转储) - 从 SavedModel 使用 Tensorflow C++ API 进行推断