如果未选择 tableView 单元格时按下按钮,则显示警报消息 [英] Display alert message if button is pressed when no tableView cells selected
问题描述
我有一个为单元格启用多个选择的 tableView.
I have a tableView that has multiple selections enabled for the cells.
TableViewController 还包含一个带有 BarButtonItem 的导航栏.当这个按钮被选中时,另一个 UITableViewController 被打开.
The TableViewController also contains a navigation bar with a BarButtonItem. When this button is selected another UITableViewController is opened.
我想添加一个参数,如果没有对 UITableView 进行选择,nextButton
将触发一条警告消息,提示用户必须选择一行或更多行.
I would like to add a parameter where if no selections are made to the UITableView than the nextButton
will trigger an alert message saying that the user must select a row or more.
这样的事情怎么办?
目前,在 didSelectRowAt 方法中,我启用了一个复选标记附件:
Currently, in the didSelectRowAt method, I have a checkmark accessory enabled:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
推荐答案
1. 检查tableView
是否为空,可以检查array您用来填充
/tableView
的 model
是否为空.
1. To check if the tableView
is empty, you can check if the array
/model
that you're using to fill the tableView
is empty or not.
假设arr
是我们用作tableView
的dataSource
的array
,
Let's suppose arr
is the array
we're using as dataSource
for tableView
,
var arr = [String]()
2. 接下来,对于 tableView
中选定的 indexPaths
,您只需检查 indexPathsForSelectedRows
是否为空与否.
2. Next, for selected indexPaths
in the tableView
, you simply need to check if indexPathsForSelectedRows
is empty or not.
如果为空,则显示 UIAlertController
,否则根据您的要求导航到另一个 UITableViewController
.
If empty, then show UIAlertController
, otherwise navigate to another UITableViewController
as per your requirement.
现在,结合上述所有条件,nextButton
的 @IBAction
如下所示,
Now, combining all the above conditions, the @IBAction
for nextButton
goes like,
@IBAction func onTapNextButton(_ sender: UIBarButtonItem) {
if arr.isEmpty || (tableView.indexPathsForSelectedRows != nil && !tableView.indexPathsForSelectedRows!.isEmpty) {
//navigate to another UITableViewController
} else {
//Show Alert here...
let alert = UIAlertController(title: "Alert..!!", message: "You must select atleast 1 row before proceeding.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
这篇关于如果未选择 tableView 单元格时按下按钮,则显示警报消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!