1
有人可以幫助我瞭解我需要添加哪些內容以獲取用戶位置和地標之間的距離嗎?我只是不確定要在distanceLabel.text中更改哪些內容才能將數字更改爲每個地標。謝謝!Swift MKMapItems距用戶的距離位置
import UIKit
import MapKit
class ListedMapTableViewController: UITableViewController, CLLocationManagerDelegate {
var mapItems: [MKMapItem]!
var userLocation = CLLocationManager()
let distanceFormatter = MKDistanceFormatter()
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mapItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath) as! ListedTableViewCell
// Configure the cell...
let row = indexPath.row
let item = mapItems[row]
cell.nameLabel.text = item.name
cell.detailLabel.text = item.phoneNumber
let distanceInMeters : Double = self.userLocation.location!.distance(from: mapItems[row].placemark.location!)
let distanceInMiles : Double = ((distanceInMeters.description as String).doubleValue * 0.00062137)
cell.distanceLabel.text = "\(distanceInMiles.string(2)) miles away"
return cell
}
}
extension String {
var doubleValue: Double {
return (self as NSString).doubleValue
}
}
//formats a double's decimal places
extension Double {
func string(_ fractionDigits:Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = fractionDigits
formatter.maximumFractionDigits = fractionDigits
return formatter.string(from: NSNumber(value: fractionDigits))!
}
}
只是改變了NSNumber(value:self))! – LBIMBA