0

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

我想UITableView在我的自定义 tableview 上订购我的 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;
}
4

3 回答 3

0

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

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

于 2013-10-18T12:14:14.607 回答
0

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

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

如果要更改结果的顺序,请反转数组。(通常用 a 完成reverseObjectEnumerator)。

于 2013-10-18T12:15:15.770 回答
0

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

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

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

于 2013-10-21T17:15:47.590 回答