距離を計算してセルをソートしようとしています。私は、構造体の場面で距離でセルを並べ替える
struct Sal {
var name:String
var coordinatesLat: CLLocationDegrees
var coordinatesLong: CLLocationDegrees
//var distance?
}
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
}
シーンB
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
}
は、私は私がシーンBにキロで距離を表示するには、シーンAから関数を呼び出していますセルで表示される距離でソートしようとしていますが、ソート方法についてはわかりません。それは名前だった場合、私はちょうど
sals.sortInPlace ({ $0.name < $1.name })
を行うことができますが、それは離れて構造体のではありませんので、私は
sals.sortInPlace ({ $0.distance < $1.distance })
を行うことはできません。私はそれを構造体から分離する必要がありますか?もしそうなら、どのように?
私も空の配列を作成し、そのように
var distance = [Double]()
self.distance.append(distanceKm) // inside cellForRowAtIndexPath
distance.sortInPlace ({ $0 < $1 })
をソートする配列に距離を追加しようとしたが、それはあなたの距離計算が含まれているように、これは
_cells_はソートしません。 _model data_をソートし、テーブルビューをリロードします。 'cellForRowAtIndexPath'はこの並べ替えを行う場所ではありません。あらかじめモデルデータ上で行う必要があります。 – matt
だから私は何とか構造体に距離を追加し、私の作成した配列からソートする必要がありますか?それが意味をなさないならば、 – luke
あなたは 'sals'が何であるか説明しませんが、Salの配列であると仮定します。それでは、配列を並べ替えるだけです。しかし、 'cellForRow'ではこれをしません。 – matt