ios - 在 TableView 中按距离排序

标签 ios swift uitableview sorting

我正在尝试按离用户最近的距离对 tableView 的结果进行排序。我已经将距离和函数分开来填充距离,以便更好地掌握我的数据操作。我觉得它应该很简单,但我知道我想念它。

距离函数是这样的:

func calculateDistance(userlat: CLLocationDegrees, userLon:CLLocationDegrees, venueLat:CLLocationDegrees, venueLon:CLLocationDegrees) -> Double {
    let userLocation:CLLocation = CLLocation(latitude: userlat, longitude: userLon)
    let priceLocation:CLLocation = CLLocation(latitude: venueLat, longitude: venueLon)
    //let distance = String(format: "%.0f", userLocation.distance(from: priceLocation)/1000)
    return userLocation.distance(from: priceLocation)/1000
}

填充数据函数:

func populateData() {
    //Pulls TableData for UITableView
    DataService.ds.REF_VENUE.observe(.value, with: { (snapshot) in
        self.posts = [] // THIS IS THE NEW LINE

        if snapshot.exists(){
            if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
                for snap in snapshot {
                    if let snapValue = snap.value as? [String:AnyObject],
                        let venueLat = snapValue["LATITUDE"] as? Double,
                        let venueLong = snapValue["LONGITUDE"] as? Double
                    {
                        let distance = self.calculateDistance(userlat: self.userLatt, userLon: self.userLonn, venueLat: venueLat, venueLon: venueLong)
                        if distance <= 2 {
                            let key = snap.key
                            let post = Post(postKey: key, postData: snapValue)
                            self.posts.append(post)
                        self.posts.sort(by: (posts, distance)) //Where I'm trying to sort

                        }
                    }
                }

                self.getDataForMapAnnotation()
            }
            self.tableView.reloadData()

        }
    })
}

我不确定我是否可以对字典数组进行排序,但最终目标是让 tableView 显示离用户最近的地点。如果您有任何建议,请告诉我!

最佳答案

如果将计算的距离添加为 Post 类/结构的属性,则按距离对帖子数组进行排序将非常简单。使用the Swift shorthand syntax for closures ,您的排序函数可能如下所示:

self.posts.sort {
    return $0.distance < $1.distance
}

这将按距离升序对帖子数组进行排序。

关于ios - 在 TableView 中按距离排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081460/

相关文章:

ios - iOS5 上的 FBConnect 和 ARC

ios - 如何创建一个计时器以固定的间隔重新加载tableView?

ios - IQKeboard 管理器在转到上一个文本字段时留下大量顶部空间

swift - 核心蓝牙用数据创建CBUUID

arrays - 无法分配 String 类型的值 :NSObject to type String:NSObject

swift - 如何区分自定义单元格中的两个文本字段?

ios - 在一个屏幕上有一些 UITableViews 和一些 UICollectionViews

ios - 将 segue 添加到动态创建的单元格

ios - 如何从 UITableViewCell 中的 Switch 捕获事件?

ios - 异步加载图片,奇怪的问题