与 UITableView 单元格和当前位置的距离

Posted

技术标签:

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

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

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

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

提前致谢。

【问题讨论】:

那有什么问题? 我在问我是否应该在应用程序开始时或在查看表格视图中的特定位置时计算从当前位置到表格视图中所有位置的所有距离?当用户旅行时,我应该何时更新这些距离? 【参考方案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: 在重新计算排序之前你可以做任何你想做的事情的方法。

以上是关于与 UITableView 单元格和当前位置的距离的主要内容,如果未能解决你的问题,请参考以下文章

按计算距离排序 UITableView 单元格

添加单元格和使用 UITableView 滚动时出现图形故障

UITableView 错误的图像加载了自定义单元格和 UIView

具有自定义单元格和多节数组数据的 Swift UITableView

iPhone-如何将 Storyboard 与自定义 UITableView 单元格和 CellWithIdentifier 一起使用

在 PFQueryTableViewController 中删除单元格和 [self loadObjects] 时,在 -[UITableView _endCellAnimationsWithCont