You need to enable JavaScript to run this app. 跨类计算TableView各IndexPath对应职位的用户距离 出现错乱及空值问题
优惠活动
大模型
产品
解决方案
定价
更多

跨类计算TableView各IndexPath对应职位的用户距离 出现错乱及空值问题

开发需求说明
  • 核心目标:计算用户与列表中每个单元格对应职位位置的距离,适配UITableView的单元格复用逻辑
  • 原有方案缺陷:此前直接在TableViewCell类内部计算距离的方案,在TableView滚动时会出现距离结果持续变动的问题,因此尝试将距离计算逻辑迁移到独立的CalculateDistance类中实现
现有实现代码

CalculateDistance 距离计算类

class CalculateDistance: NSObject, CLLocationManagerDelegate{
    
    var reloading:Reloading?
    let location = CLLocationManager()
    var job: Job!
    var Distance: String = ""
    static var gettingDistance: String = ""

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let lastLocation = locations.last {
            let geocoder = CLGeocoder()
            //解析职位地址对应的坐标
            geocoder.geocodeAddressString(JobTableViewController.jobLocation) { placemarks, error in
                print(JobTableViewController.jobLocation)
                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!)
                    //获取用户当前坐标
                    let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
                    //计算两点距离,单位换算为千米
                    let distance = myLocation.distance(from: jobLocation) / 1000
                    CalculateDistance.gettingDistance = String(format: "%.01fkm", distance)
                } else {
                    CalculateDistance.gettingDistance = "Not Valid"
                }
                self.reloading?.reloadIt()
            }
        }
        self.location.stopUpdatingLocation()
        guard let _: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    }
}

职位列表控制器的单元格渲染逻辑

static var jobLocation: String = ""
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
    cell.distance.text = CalculateDistance.gettingDistance
    return cell
}
当前存在的故障
  • 单元格内的距离标签始终为空
  • 在CalculateDistance类中添加距离值打印逻辑后,没有任何相关输出,无法定位问题原因

内容的提问来源于stack exchange,提问作者SwiftyJason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 23:06:02