ios - Swift - 在 TableView 上降序打印数组

标签 ios swift uitableview

我是 Swift 的新手,目前正在尝试在 TableView 中打印数组。该代码工作正常,但它是按升序打印的(第一个单元格的索引为 0)。有没有办法按降序打印(第一个单元格应该是最后一个索引)?

如果我错了请纠正我,但我认为这是负责表格的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let gefahren = gefahreneKm[indexPath.row]
        let dateFinal = date[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineCell") as! TimelineCell

        cell.setDrivenKm(gefahreneKm: gefahren)
        cell.setDate(date: dateFinal)

        return cell
    }

最佳答案

您可以使用数组的反转版本。

let gefahren = gefahreneKm.reversed()[indexPath.row]
let dateFinal = date.reversed()[indexPath.row]

不过,我不一定推荐这样做。您可能应该在第一次创建数组时反转数组。或者创建一个辅助函数来通过索引路径获取值,这样您就不会在某个时候忘记反转数组。

func gefahren(at indexPath: IndexPath) -> Gefahren {
    return gefahreneKm.reversed()[indexPath.row]
}

缺点是在这种情况下 reversed() 实际上会创建一个新的反向数组,而不是返回给您 ReversedCollection(因为它不能由 Int 索引),所以性能会很差。最好一开始就反转。

关于ios - Swift - 在 TableView 上降序打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800652/

相关文章:

iphone - 如何在 UITableview 的部分中对 NSarray 进行排序

ios - 使用 Xcode 5 在装有 iOS 5.1.1 的设备上运行 iOS 应用程序

ios - cocos2d 视网膜支持不再工作

objective-c - 只显示很少的cell时,是否需要实现可重用的UITableViewCells的出队机制?

swift - 在 swift 3 中安装带有 pod 的框架时出现错误 "No such module"

ios - 如何拉伸(stretch)使用 UIBezierPath 绘制的线?

iOS滚动到 View 文本字段之外

ipad - 我需要Mac OS X 10.6才能为iPad开发吗?

iphone - 像 Cocoa 一样抽象 UIViewController

ios - 显示来自 URL 的图像,Swift 4.2