首页 > 解决方案 > 如何打印与选中的复选标记关联的单元格文本?

问题描述

本质上,我有一个用 JSON 数据填充的 tableView,每一行都包含一个单选按钮,如下面的代码所示UITableViewCell.EditingStyle(rawValue: 3)!

我希望能够选择一行,并让应用程序在item.num选择后仅打印所选行的文本。

tableView 控制器的以下代码:

import UIKit

class ToFacilityTableViewController: UITableViewController {
    var driverName = UserDefaults.standard.string(forKey: "name")!
    var sections = [Section]()

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchJSON()

        self.tableView.setEditing(true, animated: false)
        //Adds Shadow below navigation bar

        self.extendedLayoutIncludesOpaqueBars = true
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
        navigationController?.navigationBar.prefersLargeTitles = true


        self.tableView.allowsMultipleSelection = true
        self.tableView.allowsMultipleSelectionDuringEditing = true

        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
        tableView.refreshControl = refreshControl
    }

    private func fetchJSON() {
        guard let url = URL(string: "https://example/example/example"),
            let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
            else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "driverName=\(value)".data(using: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data else { return }


            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let res = try decoder.decode([Portfolios].self, from: data)
                let grouped = Dictionary(grouping: res, by: { $0.customer })
                let keys = grouped.keys.sorted()
                self.sections = keys.map({Section(name: $0, items: grouped[$0]!)})

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            catch {
                print(error)
            }

            }.resume()

    }

    @IBAction func confirmPressed(_ sender: Any) {
        let selectedRows = self.tableView.indexPathsForSelectedRows
        print(selectedRows)

    }


    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return UITableViewCell.EditingStyle(rawValue: 3)!
    }


    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        return section.items.count


    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].name
    }

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

        cell.multipleSelectionBackgroundView = UIView(frame: cell.frame)
        cell.multipleSelectionBackgroundView?.backgroundColor  = .clear

        let section = sections[indexPath.section]
        let item = section.items[indexPath.row]
        cell.textLabel?.textAlignment = .left

        let titleStr = "\(item.num) - \(item.name) - \(item.zip)"
        cell.textLabel!.text = titleStr


        return cell
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
        if sectionTitle == "" {
            return nil
        }

        let title: UILabel = UILabel()

        title.text = sectionTitle
        title.textColor = UIColor.white
        title.textAlignment = .center
        title.backgroundColor = UIColor(red:0.89, green:0.37, blue:0.37, alpha:1.0)
        title.font = UIFont.boldSystemFont(ofSize: 20)

        return title
    }

    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {


        }
    }


    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

这是 rawValue 向我展示的内容:

在此处输入图像描述

标签: swiftuitableview

解决方案


实施didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     // current row
     print(sections[indexPath.row])

    // for all selected rows assuming tableView.allowsMultipleSelection = true
    tableView.indexPathsForSelectedRows?.forEach {
      print(sections[$0.row])
    }
}

推荐阅读