I am trying to calculate the distance between two Coordinates and showing them inside an Label of an UITableViewCell.
So far so good - my problem now is, that every time I scroll the tableview, the value of the label gets changed and the distances get completely mixed up...
What I've read so far is, that this problem gets created due dequeuing and reusable data
But before I speak any further, this is my code:
class JobTableViewCell: UITableViewCell, CLLocationManagerDelegate {
@IBOutlet weak var distance: UILabel!
let location = CLLocationManager()
static var takenLocation: String?
override func layoutSubviews() {
super.layoutSubviews()
location.delegate = self
self.location.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastLocation = locations.last {
let geocoder = CLGeocoder()
//get job coordinates
geocoder.geocodeAddressString(job.location) { placemarks, error in
let placemarkW = placemarks?.first
if let placemark = placemarkW
{
let lat = placemark.location?.coordinate.latitude
let lon = placemark.location?.coordinate.longitude
let jobLocation = CLLocation(latitude: lat!, longitude: lon!)
//get user coordinates
let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
//get distance between coordinates
let distance = myLocation.distance(from: jobLocation) / 1000
self.distance.text = String(format: "%.01fkm", distance)
self.job.distance = distance
//JobTableViewCell.takenLocation = String(format: "%.01km", distance)
} else {
self.distance.text = "Not Valid"
self.job.distance = 0.0
}
self.reloading?.reloadIt()
}
}
self.location.stopUpdatingLocation()
guard let _: CLLocationCoordinate2D = manager.location?.coordinate else { return }
}
}
I don't have any trouble calculating or showing the distance, my only problem is that I don't know how to reuse the LabelData(if this is even the correct approach :/ )
As far as I know, I need to go over to the TableViewController and write something like cell.distance.text = idonwknowwhat, but that's the point where I stuck
UPDATE:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath) as! JobTableViewCell
let job = jobs[indexPath.row]
cell.job = job
cell.jobHeader.text = job.postHeader //just leave this line so the function is not empty
//cell.cellDelegate = self
return cell
}
question from:
https://stackoverflow.com/questions/65831084/calculate-distance-between-two-coordinates-and-display-it-inside-an-label-of-an 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…