swift - 如何打印与选中的复选标记关联的单元格文本?
问题描述
本质上,我有一个用 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 向我展示的内容:
解决方案
实施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])
}
}
推荐阅读
- reactjs - 如何使链接出现在我制作的组件上方?
- django - 在 heroku 中更改 DATABASE_URL
- python - 当函数的输入为数组时,如何确定 scipy.optimize.fmin 的 xtol?
- mysql - 如何使用条件 A + B 在 Active Record 中搜索
- bash - 使用 sed 查找和替换行
- angularjs - 使用复选框的 html 组件中的“$event.target.checked”问题
- java - 这里的变量count,是在初始化后声明的,这个在JAVA中叫什么概念,在哪里可以了解更多呢?
- java - Spring ClassCastException?
- javascript - 全局变量不起作用 - 节点 14.15.3
- pandas - 如何从具有 100k 行的列中的字符串中提取字符