您好,有一个 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
}
最佳答案
您可以像这样利用“UITableViewDelegate”willDeselectRowAt 方法:
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
guard tableView.indexPathsForSelectedRows?.count ?? 0 == 1 else { return indexPath}
let alertController = UIAlertController(title: "Error", message: "You must keep at least one cell selected", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return nil
}
关于ios - 在 UITableView 中至少选择一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086585/