我有一个简单的结构,我将其分组并插入到带有部分和单元格标题的表格视图中。我想从 IndexPath(row: , section: ) 的数据中获取索引,然后将其用于 tableView.scrollToRow。
import UIKit
class ViewController: UIViewController {
var sorted_data = Array<(key: String, value: Array<structdata>)>()
struct structdata {
var id: Int
var row: String
var section: String
}
override func viewDidLoad() {
super.viewDidLoad()
let someArray : [structdata] = [
structdata(id: 1, row: "hello1", section: "monday"),
structdata(id: 2, row: "hello2", section: "friday"),
structdata(id: 3, row: "hello3", section: "monday"),
structdata(id: 4, row: "hello4", section: "friday")
]
let grouped = Dictionary(grouping: someArray, by: { $0.section })
sorted_data = grouped.sorted { $0.key.localizedStandardCompare($1.key) == .orderedDescending }
print(sorted_data)
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return sorted_data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sorted_data[section].value.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(sorted_data[section].key)"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let ppp = sorted_data[indexPath.section].value[indexPath.row]
cell.textLabel?.text = ppp.row
return cell
}
}
如何从具有最高id的sorted_data中获取节和行索引? = ID:4
问题有点不清楚,我不知道确切的最终结果是什么,所以这个答案有点猜测。
首先找到你能做到的最大id值的对象
someArray.max(by: { $0.id < $1.id })
然后我们可以使用该对象的
id
和 section
属性来查找与节和行匹配的第一个索引
类似这样的事情
if let maxObject = someArray.max(by: { $0.id < $1.id }) {
let sectionIndex = sorted_data.firstIndex(where: { $0.key == maxObject.section })!
let rowIndex = sorted_data[sectionIndex].value.firstIndex(where: { $0.id == maxObject.id })
print(sectionIndex, rowIndex)
}