【问题标题】:Order UITableView cells by calculated distance按计算距离排序 UITableView 单元格
【发布时间】:2013-10-18 12:05:15
【问题描述】:

我对 iOS 开发很陌生。我遇到了一个问题。

我想在我的自定义 tableview 上订购我的 UITableView Descending by Distance。 我通过查询我的 parse.com 数据库获得日期。 然后,在创建单元格时,我计算我当前位置与数据库对象的地理点位置之间的距离。 --> 效果很好!

但是如何按计算的距离对 TableView 进行降序/升序排序?

这是我的代码,我在其中创建单元格并计算距离:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    static NSString *simpleTableIdentifier = @"stationCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    } 
    // Configure the cell
    PFFile *thumbnail = [object objectForKey:@"img"];
    PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
    thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
    thumbnailImageView.file = thumbnail;
    [thumbnailImageView loadInBackground];

    UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
    nameLabel.text = [object objectForKey:@"name"];

    UILabel *adressLabel = (UILabel*) [cell viewWithTag:102];
    adressLabel.text = [object objectForKey:@"adress"];

    // DISTANCE Calculation

    [PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *currentLocationGeoPoint, NSError *error) { //Get current Location
        if (!error) {

            PFGeoPoint *distanceGeoPoint = [object objectForKey:@"location"];

            double distanceDouble  = [currentLocationGeoPoint distanceInKilometersTo:distanceGeoPoint];
            NSLog(@"Distance: %.1f",distanceDouble); // %.1f - limits to 1.1

            UILabel *distanceLabel = (UILabel*) [cell viewWithTag:103];
            distanceLabel.text = [NSString stringWithFormat:@"%.1f", distanceDouble];

        }
    }];

    return cell;
}

【问题讨论】:

    标签: ios objective-c uitableview parse-platform


    【解决方案1】:

    cellForRowAtIndexPath 中,对行进行排序为时已晚,当调用该方法时 单元格即将显示

    你应该在获取元素后对其进行排序,并将排序后的数组用作表格视图数据源。

    【讨论】:

      【解决方案2】:

      将您的模型数据 (MVC) 与您的视图更新(cellForRowAtIndexPath 中的代码)分开。即不要从cellForRowAtIndexPath 拨打geoPointForCurrentLocationInBackground。执行一次即可获取所有位置数据。

      现在,您应该有一个位置数据数组。在cellForRowAtIndexPath 中,您可以使用indexPath 从该数组中获取数据。

      当你想改变结果的顺序时,反转数组。 (通常使用reverseObjectEnumerator 完成)。

      【讨论】:

        【解决方案3】:

        谢谢韦恩! 我将 MVC 和视图更新分开。 然后我更改了初始查询并使用以下函数按距离对结果进行排序:

        [query whereKey:@"location" nearGeoPoint:userGeoPoint];
        

        http://parse.com/docs/ios/api/Classes/PFQuery.html#//api/name/whereKey:nearGeoPoint:

        【讨论】: