ios - 如何在 Swift 4 中按列值对 UITableView 进行排序?

标签 ios swift uitableview sorting

我有一个应用程序可以显示比特币的价格。我想在单击列标题时进行排序。

enter image description here

我正在尝试执行此操作,已响应点击,但没有任何反应,该列继续未排序。

struct info {
        let name: String
        let coin: String
        let change: Double
        let price: Double
    }

var ticker: Array<info> = []

@objc func tapChangeFunction(sender: UITapGestureRecognizer) {
        self.ticker.sorted(by: {
            $0.change > $1.change
        })

        DispatchQueue.main.async {
            self.table.reloadData()
        }
    }

最佳答案

看来您刚刚忘记将排序后的数据分配回模型:

self.ticker = self.ticker.sorted(by: {
    $0.change > $1.change
})

sorted(by:) 返回一个排序后的新数组,旧的没有修改,阅读docs :

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

或者使用变异版本 sort(by:) ( docs ):

Sorts the collection in place, using the given predicate as the comparison between elements.

self.ticker.sort(by: {
    $0.change > $1.change
})

旁注:

您不必异步调度 reloadData,您已经在主线程上了。

关于ios - 如何在 Swift 4 中按列值对 UITableView 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340628/

相关文章:

ios - 获取Major/Minor值 'without'监控?

ios - 将用 Swift 3.0 编写的模块迁移到 Swift 2.3?

swift - 将 "correct"数据从 UITableViewController 中选定的单元格传递到 ViewController

ios - 将数据从 plist 加载到两个 TableView

ios - UITabBarController subview Controller 重置-Swift2 iOS

ios - 向 MKMapView 注释添加操作

ios - 如何将 appDelegate.m(Objective-C) 中的内容导入到 Swift 项目中?

ios - 如何在Alamofire的上传方法中上传非字符串值的参数

ios - Swift - 覆盖 UIViewController 与 UITableViewController 中的函数

ios - SpriteKit : Collisions with 300 nodes, FPS 非常低