我可以在表格上顯示位置列表。但現在我想根據當前位置對其進行排序。在表格上顯示與用戶最近的位置列表
這是我怎麼顯示我的位置:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)
let location = LocationManager.shared.locations[indexPath.row]
cell.textLabel?.text = location.name
return cell
}
我試圖實現我的Location
類,我從https://stackoverflow.com/a/35200027/6362735得到這個距離,但我不知道我需要什麼未來,以及如何做把它分類。
這裏是我的位置類:
class Location {
var name: String
var latitude: Double
var longitude: Double
var location:CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
init?(json: JSON) {
guard let name = json["name"] as? String, let latitude = json["latitude"] as? Double, let longitude = json["longitude"] as? Double else { return nil }
self.name = name
self.latitude = latitude
self.longitude = longitude
}
func distance(to location: CLLocation) -> CLLocationDistance {
return location.distance(from: self.location)
}
}
顯示當前位置:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
}
感謝您的回覆。但是,你能詳細說明我的應用程序在哪裏調用? – mninety5
這取決於您的應用程序的結構。如果你有一個按鈕或什麼東西觸發了過濾操作,你應該把它放在那裏。如果您希望您的位置始終按距離排序,則可以將其放置在TableView的控制器中,例如「viewDidLoad」。我會在兩種情況下更新答案。 – jvrmed
但是我在參數中加入了什麼?當我使用你的排序功能時,它只是說:'參數'缺少參數'調用'。它期待一個'CLLocation'。 – mninety5