ios - 将排序后的数据管理到 TableViewController 中的索引部分和单元格中

标签 ios swift uitableview

如何构建类似 iPhone 的“联系人”列表的表格 View ?

我的原始数据采用 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
........
........

数据按文章排序。排序:

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作为排序键,在tableview上按章节标题(A,B,C..)显示文章信息,滚动索引表A~Z,并引导到下一个 View 单击单元格时显示详细数据。

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
}

最佳答案

当您的数组准备好使用后,您可以使用此方法对数组元素进行排序。

articles = articles.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == ComparisonResult.orderedDescending }

关于ios - 将排序后的数据管理到 TableViewController 中的索引部分和单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50664275/

相关文章:

ios - 以编程方式将目标添加到按钮会引发错误 "unrecognized selector sent to class"

iphone - AFNetworking 多次上传减慢主线程

cocoa - 如何更改 Nib 上 NSSplitView 分隔线的颜色?

快速在 UITableView 中异步加载图像 - 顶部单元格没有图片

ios - 由于未捕获的异常 'NSInternalInconsistencyException' 终止应用程序,- Swift 3

ios - 当我从详细 View 返回时图像数组加倍

ios - 我如何使用我的 iPhone/iPad 应用程序生成二维码?

ios - 一次检测多个触摸(Swift)

swift - NSData 变量不保存到 CoreData

iphone - 使用 "tableView:sectionForSectionIndexTitle:atIndex:"帮助滚动到 TableViewHeader?