按距离排序单元格

时间:2016-03-28 14:55:53

标签: ios swift uitableview sorting

所以我试图按计算的距离对细胞进行排序。我有一个结构

for (Shape s : shapeArr) {
    System.out.printf("Found a shape with area %.2f", s.calcArea());
}
场景A中的

struct Sal {
var name:String
var coordinatesLat: CLLocationDegrees
var coordinatesLong: CLLocationDegrees
//var distance?
}

场景B

func distanceFromLocation(location: CLLocation) -> CLLocationDistance {

    // Find lat and long coordinates of current location
    let getLat = self.location.latitude
    let getLon = self.location.longitude
    let currentLocation =  CLLocation(latitude: getLat, longitude: getLon)
    // Calculate distance from current location to sal
    let distance = currentLocation.distanceFromLocation(location)
    return distance
}

我调用场景A中的函数来显示场景B中Km的距离。我正在尝试按照单元格中显示的距离对它们进行排序,但我不确定如何对它们进行排序。如果它是我可以做的名字

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SalCustomCell

    let name = sals[indexPath.row].name
    cell.name.text = name

    // Calculate distance between current location and sal
    let salLocation = CLLocation(latitude: sals[indexPath.row].coordinatesLat, longitude: sals[indexPath.row].coordinatesLong)

    // Display distance in cell.
    let distanceM = viewController.distanceFromLocation(salLocation)
    let distanceKm = round(distanceM/1000)
    cell.distance.text = String(distanceKm) + "km"
    return cell
}

但我做不到

sals.sortInPlace ({ $0.name < $1.name })

因为它不是结构的一部分。我是否需要将它与结构区分开来?如果是这样的话?

我还试图创建一个空数组并将距离追加到数组中以便按那种方式排序

sals.sortInPlace ({ $0.distance < $1.distance })

但这没有成功

1 个答案:

答案 0 :(得分:1)

重写Sal,使其包含距离计算功能,如下所示:

struct Sal {
    var name:String
    var coordinatesLat: CLLocationDegrees
    var coordinatesLong: CLLocationDegrees
    func distanceFromLocation(location: CLLocation) -> CLLocationDistance {
        // ...
    }
}

现在你的Sal阵列有一个可以排序的Sal功能。