我是 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/