我有一个从核心数据实体填充的 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)"
现在,我如何根据与当前位置的距离对位置进行排序。
我可以轻松地按名称或存储在核心数据中的任何值进行排序,但需要根据检索到的数据计算距离,当我进行计算时,它会很晚,所以对单元格进行排序
如果可以请帮忙
非常感谢您
最佳答案
例如,您的 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)})
这里的想法是在 swift 中使用 Array 的 .sort 特性来对列表进行排序。您必须定义 .getDistance() 才能正确排序数组。
如果您有一个 NSManagedObject 来获取 tableviewcell,您可以使用扩展将 getDistance 添加到您的 NSManagedObject。 例如,你的类名为“Foo”(包含名称、纬度、经度、时间戳),你可以添加一个扩展名,如
extension Foo {
func getDistance(CLLocation current) {
//your calculation using Location API
}
}
关于swift - 在 Swift 中按距离对 UItableview 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768223/