ios - 将排序后的数据管理到 TableViewController 中的索引部分和单元格中
问题描述
如何构建一个类似于 iPhone 的“联系人”列表的 tableview?
我的原始数据在 中JSON
,它被下载并打包到模型类的一个对象中Article.swift
。“文章”是它的元素。
article.name = rawData["A_Name_Ch"] as! String
article.name_EN = rawData["A_Name_En"] as! String
article.location = rawData["A_Location"] as! String
article.image_URLString = rawData["A_Pic01_URL"] as? String
........
........
数据按article.sorted排序:
func downLoadLatestArticles(){
Article.downLoadItem { (articles, error) in
if let error = error {
return
}
if let articles = articles {
self.articles = articles.sorted(by: { $0.name_EN! < $1.name_EN! })
}
}
}
我们想使用 article.name 作为 key 进行排序,在 tableview 上按 section title(A,B,C..) 显示文章的信息,滚动侧索引表 A~Z,并用详细数据引导下一个视图单击单元格时。
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return articles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableCell", for: indexPath) as! ListTableCell
var article : Article
let imageURL: URL?
if let imageURLString = article.image_URLString {
imageURL = URL (string: imageURLString)
}
else { imageURL = nil }
if let c = cell as? ListTableCell {
c.nameLabel?.text = article.name;
c.name_ENLabel?.text = article.name_EN;
c.locationLabel?.text = article.location
}
return cell
}
解决方案
在您的 Array 准备好使用后,您可以使用此方法对您的数组元素进行排序。
articles = articles.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == ComparisonResult.orderedDescending }
推荐阅读
- java - android.content.Context.getPackageName() 在空对象引用上
- stata - 在Stata的相关矩阵中添加均值和sd列
- c# - 将 PBIX 文件(从 blobstorage)导入 PowerBI 组时出现错误 (404)
- r - 向量与子向量长度 n 的组合
- c# - 使用 Moq 模拟 Fluent 界面
- python - 如何在 python 中打印使用 QtDesigner 设计的滚动 GUI?
- flutter - 如何使用“lamp 0.0.6”在 Android 上的 Flutter 中打开手机的灯?
- android - 如何通过 ADB 获取电子邮件地址列表
- ios - iOS13外屏镜像,报错:setScreen不应该被调用
- ruby-on-rails - 使用 Heroku 部署我的 Rails 应用程序时找不到 jquery 和 jquery_ujs