如何打印与选中的复选标记关联的单元格文本?

时间:2019-06-19 17:19:00

标签: swift uitableview

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

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

tableView Controller的以下代码:

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向我显示的内容:

enter image description here

1 个答案:

答案 0 :(得分:0)

实施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])
    }
}