【问题标题】:Sorting UItableview by distance in Swift在 Swift 中按距离对 UItableview 进行排序
【发布时间】:2015-04-21 09:32:23
【问题描述】:

我有一个从核心数据实体填充的UITableView,以显示位置名称以及这些位置的经纬度。

我已经设法计算出用户到存储位置的距离并显示了距离。

        var templat = NSString(string: location.lat)
        var templong = NSString(string: location.long)
        var distinationCoords: CLLocation =  CLLocation(latitude: templat.doubleValue, longitude: templong.doubleValue)
        var distance: CLLocationDistance = distinationCoords.distanceFromLocation(mypoi.sharedlocation)
        classdistance = distance / 1000

        cell.customCellSubTitle?.text = "\(distance)"

现在,如何按与当前位置的距离对位置进行排序。

我可以轻松地按名称或存储在核心数据中的任何值进行排序,但是需要根据检索到的数据计算距离,当我进行计算时会为时已晚,因此对单元格进行排序

如果可以的话请帮忙

非常感谢您

【问题讨论】:

  • 你在使用 NSFetchResultController 吗?如果是,则将距离存储到 coredata 并使用 NSSortDescriptor 对其进行排序。如果您需要更多帮助,请告诉我
  • 您无法在 NSSortDescriptor 中计算距离,因为您必须使用 CLLocation 和 CLLocationDistance。
  • 你的核心数据实体有哪些属性?
  • 我正在使用 NSFetchResultController,你不能在核心位置存储距离,因为它一直在改变。必须在显示 uitableview 时才计算。
  • 我的实体有以下属性:名称、纬度、经度、时间戳

标签: swift sorting distance


【解决方案1】:

例如,您的 tableview 由具有结构的数据列表填充:

struct Position {
    var latitude : Double
    var longitude: Double
    //you add a function to compare a position to another
    func getDistance(CLLocation current) -> double {
        //calculate the distance here
    } 
}

那么,你的职位列表

var positions = ... the list of positions ...
positions.sort({$0.getDistance(currentPos) > $1.getDistance(currentPos)})

这里的想法是快速使用 Array 的 .sort 功能对列表进行排序。您必须定义 .getDistance() 才能正确排序数组。

如果你有一个 NSManagedObject 来获取 tableviewcell,你可以使用扩展将 getDistance 添加到你的 NSManagedObject。 例如,您的类名为“Foo”(包含名称、纬度、经度、时间戳),您可以添加类似的扩展名

extension Foo {
    func getDistance(CLLocation current) {
        //your calculation using Location API
    } 
}

【讨论】:

  • 我的 tableview 使用 coreData 而不是 list let location = fetchedResultsController.objectAtIndexPath(indexPath) as myLocations
  • 您可以在 Swift 中使用扩展来为您的 NSmanagedObject 添加函数 getDistance。查看我的更新答案