问题描述
我尝试在TableViewCell内的标签中显示两个坐标之间的距离,但是每次滚动时,标签的数据都会发生变化...我知道我需要使用可重复使用的标识符,但是我尝试过的所有操作都不会工作...
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.categorie.text = job.categorie
cell.distance.text = JobTableViewCell.takenLocation
return cell
}
然后我计算TableViewCell类内部的距离
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 }
}
我听说不重复使用Cells是一个非常糟糕的主意,那么有什么办法可以解决我的问题? (顺便说一下,分类标签有效)
编辑 新的计算类别:
class Calculatedistance: NSObject,CLLocationManagerDelegate{
var reloading:Reloading?
let location = CLLocationManager()
var job: Job!
var nodistance: String = ""
static var gettingdistance: String = ""
func locationManager(_ manager: CLLocationManager,longitude: lastLocation.coordinate.longitude)
//get distance between coordinates
let distance = myLocation.distance(from: jobLocation) / 1000
Calculatedistance.gettingdistance = String(format: "%.01fkm",distance)
} else {
self.nodistance = "Not Valid"
}
self.reloading?.reloadIt()
}
}
self.location.stopUpdatingLocation()
guard let _: CLLocationCoordinate2D = manager.location?.coordinate else { return }
}
}
解决方法
- 创建一个单独的类以计算位置。 Cell的工作是显示UI并与用户进行交互。
- 在您的代码中,地理编码器将在完成时为您提供地标,它可以异步工作,这意味着将加载TableView单元格,但地标以后再来计算距离,获取距离后,调用tableView.reloadData()(不要忘记在主队列中调用它。
如果您需要更多信息,请随时提问!