ios - 选择不同部分中的行时如何显示错误消息

标签 ios swift uitableview

基本上我有一个由部分分隔的 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/

相关文章:

ios - 如何卸载 NSBundle?

swift - 如何重置 UICollectionVIewCell 的背景颜色

ios - 如果键盘未关闭,则使用搜索栏时进行排序会更改目标 View Controller 布局

ios - 文本字段标签和表格 View

ios - 未调用 XMLParser 委托(delegate)方法

iphone - 将 UIView 转换为 UITableView

ios - 不带 TabBarController 的选项卡栏 - 在 Storyboard 中为选项卡栏项目添加 View Controller

swift - 如何从视频文件 Cocoa Swift 获取图像缓冲区数组

ios - UINavigationController 使用 SWRevealViewController 阻止 UITabBar

ios - 如何在Swift中放慢MapView动画的速度?