ios - 在 UITableView 中至少选择一行

标签 ios swift 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
}

最佳答案

您可以像这样利用“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/

相关文章:

iphone - Sharekit:在发布到 Facebook 时修改了 url?

iphone - 如何在另一个 UIView Controller 中显示复杂的 UIViewController?

Ios+Redlaser + 产品信息

ios - 如何在 MKMapView 中显示整个地球

ios - Swift(解析)顶部 UITableViewCell 的新行?

iphone - 如何确保应用程序已正确签名

ios - 在 SWRevealViewController 中隐藏状态栏

ios - 我找到了四种不同的方法来更改 Xcode 中的 iOS 状态栏。为什么会有这么多,有什么区别?

c# - UITableView 中的交替行颜色

快速更改 UITableView 的背景颜色