ios - UITableViewCell 排序

标签 ios uitableview

我是 Objective-C 的初学者,希望各位专家能帮帮我。我有一个 Web 服务,它使用 JSON 编码返回名称和地址。在我的应用程序方面,我有一个带有字幕样式单元格的 UITableView。我在第二个标签中显示主标签的名称和地址与当前设备位置的距离。我必须根据距离对 UITableViewCell 进行排序。我能够显示名称和距离,但不知道如何按距离排序。我将不胜感激。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    NSDictionary *info = [json objectAtIndex:indexPath.row];

    NSString *sName = [info objectForKey:@"Name"];
    NSString *sAddress = [info objectForKey:@"Address"];

    cell.textLabel.text = sName;

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:sAddress completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error){
            NSLog(@"%@", error);
        } else {
            CLPlacemark *placemark = [placemarks lastObject];

            CLLocation *restLocation = [[CLLocation alloc] initWithLatitude:placemark.location.coordinate.latitude longitude:placemark.location.coordinate.longitude];

            CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.locationManager.location.coordinate.latitude longitude:self.locationManager.location.coordinate.longitude];

            CLLocationDistance distance = [userLocation distanceFromLocation:restLocation];
            distance = distance/1000;

            NSString *sDistance = [NSString stringWithFormat: @"%@%1.2f%@",@"Distance: ",distance, @" km"];

            cell.detailTextLabel.text = sDistance;
        }

    }];

    return cell;
}

最佳答案

排序数据源而不是 Cell,在 cellForRowAtIndexPath 委托(delegate)之前稍微改变一下

json = [json sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    NSString *address1 = [obj1 objectForKey:@"Address"];
    NSString *address2 = [obj2 objectForKey:@"Address"];
    return [self distanceFromAddress:address1] > [self distanceFromAddress:address2];
}];

- (CLLocationDistance)distanceFromAddress: (NSString *)sAddress {

//Put your Geocoder method here

}

关于ios - UITableViewCell 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37055880/

相关文章:

ios - 为什么 tableview 单元格在要重复使用时开始闪烁?

objective-c - 无法从 UIButton 获取 UITouch 事件

ios - 在单个按钮单击中隐藏多个 UIButton

ios - 更新 TableViewCell 中的 UIButton State 会改变其他行

ios - Mapkit View 上的部分显示

ios - 如何在单元格中显示图像?

objective-c - 同步多个 UITableView 实例的滚动位置

swift - 如何按在快速加载数据后计算的距离对表格 View 单元格进行排序

ios - 选择单元格后 View 在不同单元格上重复

ios - 如何在 iOS 上拖放多个 uitableveiwcells?