基本上我有一个由部分分隔的 tableView。
tableView 允许多行选择,并在所有选定的行上显示一个附件 .checkmark。
如果用户开始选择一个部分下的行并尝试在不同的部分下选择不同的行,我希望出现一条警告消息并且不进行选择。
以下是目前的代码:
import UIKit
class TableViewController: UITableViewController {
var Name = UserDefaults.standard.string(forKey: "name")!
var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
navigationController?.navigationBar.prefersLargeTitles = true
fetchJSON()
self.tableView.allowsMultipleSelection = true
}
}
最佳答案
实现 UITableViewDelegate
方法 tableView(_:willSelectRowAt:)
。
使用 map(_:)
从 indexPathsForSelectedRows
获取 sections
。
检查 tableView(_:willSelectRowAt:)
中的 indexPath 的
section
是否包含在之前获取的 sections
array
使用 contains(_:)
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let sections = tableView.indexPathsForSelectedRows?.map({ $0.section }) {
if !sections.contains(indexPath.section) {
//Show Alert here....
let alert = UIAlertController(title: "Alert..!!", message: "You're selection row from Section:\(indexPath.section)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
return nil
}
}
return indexPath
}
tableView(_:willSelectRowAt:) return value : An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
关于ios - 选择不同部分中的行时如何显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809467/