CLLocationManager 不适用于 UITableView 第一页上的单元格

CLLocationManager doesn't work for cells on first page of UITableView

我正在使用 CLLocationManager 获取当前位置,并打印到 table 单元格中每个点的距离(从我得到的当前位置)。

class TableViewController: UITableViewController, CLLocationManagerDelegate, MKMapViewDelegate {

var thisLocationManager = CLLocationManager()
var myLocation = CLLocation()

...

override func viewDidLoad() {  

   ...

   if CLLocationManager.locationServicesEnabled() {
        self.thisLocationManager.requestAlwaysAuthorization()
        self.thisLocationManager.requestWhenInUseAuthorization()
        thisLocationManager.delegate = self
        thisLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        thisLocationManager.startUpdatingLocation()
    }
}

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
    myLocation = newLocation
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> SpotCell {
    let row = self.list[indexPath.row]

    let cell = tableView.dequeueReusableCellWithIdentifier("SpotCell") as! SpotCell

    if CLLocationManager.locationServicesEnabled() {
        // for checking 
        print("Row \(indexPath.row): lati \(myLocation.coordinate.latitude), long \(myLocation.coordinate.longitude)")

        let spotLocation = CLLocation(latitude: Double(row.latitude)!, longitude: Double(row.longitude)!)
        let distance = round(myLocation.distanceFromLocation(spotLocation) / 10) / 100
        cell.spotInfo.text = "\(row.spotrank), distance \(distance)km"
    } else {
        cell.spotInfo.text = row.spotrank
    }

    return cell
}

这是我用来获取当前位置的代码。
当我在 iOS9 模拟器和 运行 应用程序

上设置坐标时

对于第一个单元格,控制台显示:
第 0 行:纬度 0.0,经度 0.0
第 1 行:纬度 0.0,经度 0.0
第 2 行:纬度 0.0,经度 0.0
第 3 行:纬度 0.0,经度 0.0
第 4 行:纬度 0.0,经度 0.0
第 5 行:纬度 0.0,经度 0.0

然后当我向下滚动时...
第 6 行:纬度 51.530466,经度 -0.123833
第 7 行:纬度 51.530466,经度 -0.123833
第 8 行:纬度 51.530466,经度 -0.123833
这些是我设置的坐标。它适用于下一个单元格。

当我向后滚动时
第 2 行:纬度 51.530466,经度 -0.123833
第 1 行:纬度 51.530466,经度 -0.123833
第 0 行:纬度 51.530466,经度 -0.123833

为什么这只对第一页不起作用?

听起来您在第一页要求时没有加载必要的数据,但之后就可用了。您需要实施某种方法来检测一旦您有可用的位置,然后去(重新)设置带有该数据的单元格。

好消息是你已经有了那个方法!一旦您收到来自 func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) 的消息,请致电 self.tableView.reloadData(),您将获得数据流入!