如何根据 swift 3 中的数组选择复选标记?

2023-12-11

我有一个数组,其中选定的名称将被存储并传递到视图控制器之前,当我需要转到上一个视图控制器时,则需要选择先前选择的复选标记,但在这里它启用了最后一个选定的元素,唯一的问题是如果我选择三个,那么它不是选择三个,它只是检查标记最后一个元素,但我需要选择三个元素,任何人都可以帮助我如何为三个元素选择复选标记?

protocol ArrayToPass: class {
    func selectedArrayToPass(selectedStrings: [String])
}
class FilterSelectionViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    var productName = [String]()
    var productprice = [String]()
    var imageArray = [String]()
    var idArray = [Int]()
    let urlString = "http://www.json-generator.com/api/json/get/bOYOrkIOSq?indent=2"
    var values = [String]()
    var selected: Bool?
    var delegate: ArrayToPass?
    var nameSelection: Bool?
    var namesArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.downloadJsonWithURL()
        tableDetails.separatorInset = UIEdgeInsets.zero
        activityIndicator.startAnimating()
        tableDetails.isHidden = true
        tableDetails.dataSource = self
        tableDetails.delegate = self
        let rightBarButton = UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.plain, target: self, action: #selector(applyBarButtonActionTapped(_:)))
        self.navigationItem.rightBarButtonItem = rightBarButton
        tableDetails.estimatedRowHeight = UITableViewAutomaticDimension
        tableDetails.rowHeight = 60
        // Do any additional setup after loading the view.
    }
    func applyBarButtonActionTapped(_ sender:UIBarButtonItem!){
        self.delegate?.selectedArrayToPass(selectedStrings: values)
        navigationController?.popViewController(animated: true)
    }
    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {
                for item in jsonObj! {
                    if let itemDict = item as? NSDictionary{
                        if let name = itemDict.value(forKey: "name") {
                            self.productName.append(name as! String)
                        }
                        if let price = itemDict.value(forKey: "value") {
                            self.productprice.append(price as! String)
                        }
                        if let image = itemDict.value(forKey: "img") {
                            self.imageArray.append(image as! String)
                        }
                        if let id = itemDict.value(forKey: "id") {
                            self.idArray.append(id as! Int)
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                })
            }
        }).resume()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productName.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath) as! FilterSelectionCell
        activityIndicator.stopAnimating()
        activityIndicator.hidesWhenStopped = true
        tableDetails.isHidden = false
        cell.brandProductName.text = productName[indexPath.row]
        if nameSelection == true{
            if namesArray.count != 0 {
                print(namesArray)
                for name in namesArray{
                    if productName[indexPath.row].contains(name){
                        print(productName[indexPath.row])
                        cell.accessoryType = .checkmark
                    }
                    else {
                        cell.accessoryType = .none
                    }
                }
            }
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        selected = false
        if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
            if cell.accessoryType == .checkmark{
                cell.accessoryType = .none
                print("\(productName[indexPath.row])")
                values = values.filter{$0 != "\(productName[indexPath.row])"}
                selected = true
            }
            else{
                cell.accessoryType = .checkmark
            }
        }
        if selected == true{
            print(values)
        }
        else{
            getAllTextFromTableView()
        }
        print(values)
    }
    func getAllTextFromTableView() {
    guard let indexPaths = self.tableDetails.indexPathsForSelectedRows else { // if no selected cells just return
    return
    }

    for indexPath in indexPaths {
        values.append(productName[indexPath.row])
    }
    }

这是这个的图片


基本上不操纵视图(单元格)。使用数据模型。

struct Product {
    let name : String
    let value : String
    let img : String
    let id : Int

    var selected = false

    init(dict : [String:Any]) {
        self.name = dict["name"] as? String ?? ""
        self.value = dict["value"] as? String ?? ""
        self.img = dict["img"] as? String ?? ""
        self.id = dict["id"] as? Int ?? 0
    }
}

And 永远不要使用多个数组作为数据源。这是一个非常不好的习惯。

将数据源数组声明为

var products = [Product]()

解析 JSON 数据并进行(更好的)错误处理

func downloadJsonWithURL() {
    let url = URL(string: urlString)!
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil { print(error!); return }
        do {
            if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                self.products = jsonObj.map{ Product(dict: $0) }                
                DispatchQueue.main.async {
                    self.tableDetails.reloadData()
                }
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

in cellForRow...为标签分配名称并根据情况设置复选标记selected

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath)

    let product = products[indexPath.row]
    cell.textLabel!.text = product.name
    cell.accessoryType = product.selected ? .checkmark : .none
    return cell
}

In didSelect... toggle selected并重新加载该行

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selected = products[indexPath.row].selected
    products[indexPath.row].selected = !selected
    tableView.reloadRows(at: [indexPath], with: .none)
}

获取所有选定的项目也非常容易。

let selectedItems = products.filter{ $0.selected }

或仅获取名称

let selectedNames = products.filter{ $0.selected }.map{ $0.name }

根本不需要从网站获取任何信息view. The 控制器始终从model并使用 tableview 数据源和委托来更新view.

如果你想将数据传递给另一个视图控制器传递Product实例。它们包含所有相关信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据 swift 3 中的数组选择复选标记? 的相关文章

随机推荐

  • Tomcat 中 OpenCV 的 UnsatisfiedLinkError

    首先 我有一个在 main 方法中运行 OpenCV 的基本示例 但是 如果我在 Spring Web 控制器中使用 OpenCV 则会引发错误 在 a 中运行以下代码时 我收到 UnsatisfiedLinkErrorTomcat服务器
  • ASP.NET OnError 未捕获 ConfigurationErrorsException

    从链接到 ASP NET 站点的类库中抛出 ConfigurationErrorsException 该站点使用 Global ASAX 错误事件并重写 ASP NET 页面 OnError 受保护方法来记录所有错误 当 Configura
  • Codeigniter 活动记录中 join 返回的自定义对象

    我有这两个数据库表 地点 id name users id位置 ID姓名 我也有User and Location类 它们都扩展Model并包含一些自定义方法 例如 有一个获取全名 方法中的User class 我使用以下代码来加载数据 t
  • 如何将数据从 numpy 数组复制到另一个

    在不修改数组a的地址的情况下 将数据从数组b复制到数组a的最快方法是什么 我需要这个 因为外部库 PyFFTW 使用指向我的数组的指针 该指针无法更改 例如 a numpy empty n dtype complex for i in xr
  • 使用正则表达式搜索单词的开头

    如何编写正则表达式 可以找到以指定字符串开头的所有单词 对于前 a asasasa sasDRasas dr klklkl DR klklklkl Dr klklklkklkl 在这里我想获取所有以dr使用忽略大小写 我尝试过 但所有功能的
  • 如何将Matlab每次启动时的文件夹设置为当前文件夹?

    我想设置文件夹 Users ALJI MATLAB作为 Matlab 的默认当前文件夹 我的意思是每次启动时 Matlab 都应该指向这个文件夹 是否可以 Mac OS X 上有办法吗 我在用Matlab r2009b on Mac OS
  • javascript youtube 像滑块控件

    我有一个关于在浏览器中实现滑块控件的问题 我需要在浏览器中随时间播放数据 我将让一个 Worker 通过调用 REST api 来填充播放缓冲区 然后 UI 线程将消耗缓冲区并向用户回放数据 我想模拟 YouTube 进度 UI 控件 它在
  • 当应用凭据存储在 APK 中时,Firebase 如何防止攻击者访问 Firebase 数据库?

    因为根据多个消息来源 如何避免 APK 文件的逆向工程 不可能阻止应用程序被逆向工程 并且 Firebase 应用程序令牌存储在 APK 源中 攻击者如何不会获取这些凭据并破坏 Firebase 数据库 我担心的是 开发人员在本机应用程序和
  • 使用 dplyr 获得更好的输出——破坏函数和结果

    这是一个长久以来的疑问 但现在我真的要解决这个难题了 我一直在使用 dplyr 我认为它很棒总结变量 但是 我尝试显示数据透视表 但仅取得部分成功 Dplyr 始终报告包含所有结果的单行 有什么烦人的 我必须复制粘贴结果才能出色地组织所有内
  • GNU GAS:标签没有相对引用

    我正在写一个小引导扇区用于学习目的 这是boot S code16 text movw 0xB800 ax 0xB000 is the text screen video memory movw ax es set it as the es
  • 静态变量会阻碍数据缓存吗?

    From 用 C 优化软件 第 7 1 节 静态数据的优点是可以根据需要进行初始化 程序启动前的值 缺点是内存 整个程序执行过程中都会占用空间 即使 变量仅在程序的一小部分中使用 这使得数据 缓存效率较低 的用法static在此例外的是 它
  • 在 CUDA 统一内存多 GPU 或多处理器中使用原子算术运算

    我正在尝试实现一个使用统一内存的 CUDA 程序 我有两个统一的数组 有时它们需要原子更新 下面的问题有针对单 GPU 环境的答案 但我不确定如何扩展问题中给出的答案以适应多 GPU 平台 问题 cudaatomicAdd 示例无法产生正确
  • 爪哇芬威克树

    我尝试用 Java 实现 Fenwick 树 但没有得到预期的结果 这是我的代码 import java io import java util import java math class fenwick1 public static i
  • 需要为python打包jinja2模板

    更新 我提出了一个更好的问题和更好的答案here 我本来打算删除这个问题 但有些答案可能对未来的搜索者有用 我的问题与this 但这个答案很丑陋 需要一个目录结构 包括sharedtemplates templates templates
  • 在触发器中使用插入和删除的表

    我想编写触发器来处理插入和删除的表 我已经编写了插入触发器 CREATE TRIGGER FILL TABLE ON Person FOR INSERT AS DECLARE ID int SELECT ID p ID FROM Perso
  • 如何计算文档中的行数? [关闭]

    Closed 这个问题不符合堆栈溢出指南 目前不接受答案 我有这样的台词 我想知道我实际上有多少台词 09 16 39 AM all 2 00 0 00 4 00 0 00 0 00 0 00 0 00 0 00 94 00 09 16 4
  • C 中的逻辑运算不符合预期

    有人可以解释一下以下代码的功能吗 include
  • 如何在CSS中绘制循环箭头?

    如何使用 CSS 在中心绘制循环箭头和文本 如下图所示 我尝试过创建曲线箭头 但我不知道如何使其看起来像我想要的那样 arrow width 200px height 200px border 6px solid border radius
  • 通过 setup.exe 创建日志的 msiexec 参数不起作用

    我正在尝试从我的安装中获取使用以下命令的日志setup exe 我可以得到一个日志setup exe V l v c temp installlog txt 但我想通过x参数以及获取 额外的调试信息 当我尝试时setup exe V l v
  • 如何根据 swift 3 中的数组选择复选标记?

    我有一个数组 其中选定的名称将被存储并传递到视图控制器之前 当我需要转到上一个视图控制器时 则需要选择先前选择的复选标记 但在这里它启用了最后一个选定的元素 唯一的问题是如果我选择三个 那么它不是选择三个 它只是检查标记最后一个元素 但我需