【问题标题】:Distance from UITableView Cells and Current Location与 UITableView 单元格和当前位置的距离
【发布时间】:2015-04-03 01:21:05
【问题描述】:

我正在创建一个 iOS 应用程序,其中我有一些包含多个坐标的数据结构,并且我知道当前用户位置。我想用从用户当前位置到 TableView 中位置的距离填充 TableView 的单元格。

我想知道何时应该计算用户当前位置与 TableView 中所有位置之间的距离。我应该在应用程序启动时计算所有这些距离吗?当用户改变位置时我该怎么办?设置某种计时器来检查用户位置是否发生变化,并在每次用户位置变化时重新计算距离?

我还应该注意,我让他们能够按距离对这个 TableView 进行排序。

提前致谢。

【问题讨论】:

  • 那有什么问题?
  • 我在问我是否应该在应用程序开始时或在查看表格视图中的特定位置时计算从当前位置到表格视图中所有位置的所有距离?当用户旅行时,我应该何时更新这些距离?

标签: ios objective-c iphone uitableview


【解决方案1】:

您可以使用 CLLocationManagerDelegate 的 locationManager:didUpdateLocations: 方法。

当用户的位置更新时调用此方法,因此您可以调用您的方法从用户当前位置在 tableview 中显示数据。

下面是一些用于对 arryOfLocation 进行排序的代码。

for (int i = 0; i < arrySortByLocation.count; i++)
    {
        //Current Location Details
        NSMutableDictionary *dict = [[arrySortByLocation objectAtIndex:i] mutableCopy];

        CLLocationDegrees latitude = [dict[@"city_lat"] doubleValue];
        CLLocationDegrees longitude = [dict[@"city_lng"] doubleValue];
        CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
        CLLocationDistance distance = [appDele.userLocation distanceFromLocation:location];
        dict[@"distance"] = [@(distance) stringValue];

        //Storing as string since latitude and longitude is also string values
        //Since its a dictionary storing as NSNumber is better

        [arrySearchLocation setObject:dict atIndexedSubscript:i];
    }

    //sorting based on distance
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"distance.doubleValue" ascending:YES];
    [arrySortByLocation sortUsingDescriptors:@[descriptor]];
}

希望这会对你有所帮助..

【讨论】:

  • 感谢您的洞察力。所以我应该在用户位置发生变化时重新计算距离并再次排序?有没有办法在重新计算和排序之前检查它们与最后一个位置是否有一段距离?
  • 你可以使用 CLLocationManagerDelegate 的 locationManager:didUpdateLocations: 在重新计算排序之前你可以做任何你想做的事情的方法。
猜你喜欢
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多