Iva*_*sin 0 sorting uitableview uilabel ios swift
如何在tableView中对单元格进行排序?
我有结构和数组:
struct Converter {
let title: String
let kf: Double
}
let converterAtmo = [
Converter(title: "?????????", kf: 1),
Converter(title: "????", kf: 365.2422),
Converter(title: "??.??.??.", kf: 11.999998),
Converter(title: "???????", kf: 525948.77),
Converter(title: "????./??.????", kf: 52.177457)]
Run Code Online (Sandbox Code Playgroud)
在CellAtRowfunc中:
let cell1 = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! resultTableViewCell
let item = converterAtmo[indexPath.row]
cell1.nameResult.text = item.title
cell1.labelResult.text = String(item.kf * atmosfera)
return cell1
Run Code Online (Sandbox Code Playgroud)
最后@IBAction:
@IBAction func sortAlphabet(_ sender: Any) {
let itemSort = converterAtmo
itemSort.sorted { $0.title < $1.title }
self.tableView2.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用......
我的问题是什么?
首先,您必须声明converterAtmo为var而不是let以便您可以修改它.
然后替换:
itemSort.sorted { $0.title < $1.title }
Run Code Online (Sandbox Code Playgroud)
有:
self.converterAtmo = itemSort.sorted { $0.title < $1.title }
Run Code Online (Sandbox Code Playgroud)
在当前的实现中,您可以对模型的副本进行排序(itemSort只是您的副本self.converterAtmo),因此它对tableView后面的模型没有任何影响.您需要将已排序的数组设置回tableView数据模型.
或者甚至更好,你可以使用这个:
@IBAction func sortAlphabet(_ sender: Any) {
// `sort` method will sort the converterAtmo (`sorted` method leaves the original
// array untouched and returns a sorted copy)
self.converterAtmo.sort { $0.title < $1.title }
self.tableView2.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1444 次 |
| 最近记录: |