我有一个在表格视图上显示事件的应用程序。我有 UISegment 按字母顺序对这个表进行排序。现在我想根据从用户位置到事件位置的距离对其进行排序。
我有一个包含事件对象的数组,每个对象都包含事件名称、时间、描述等。
在我的 cellForRowAtIndexPath: 我正在这样做
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [[searchResult objectAtIndex:indexPath.row]name];
}
else{
CLLocationCoordinate2D coordinate = [_delegate getLocation];
CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
CLLocation *location = [[CLLocation alloc] initWithLatitude:[[self.events objectAtIndex:indexPath.row]latitude] longitude:[[self.events objectAtIndex:indexPath.row]longitude]];
CLLocationDistance distance = [location distanceFromLocation:userLocation];
cell.textLabel.text = [[self.events objectAtIndex:indexPath.row]name];
//self.distances = [[NSString alloc] initWithFormat: @"%f", distance];
[distances addObject:[NSNumber numberWithFloat:distance/1609.344]];
NSLog(@"distances %@", distances);
//NSString *_startTime = (NSString *)[[self.events objectAtIndex:indexPath.row]startTime];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f mi",distance/1609.344];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
一旦用户点击 UISegment:
-(void)changeSegment:(id)sender{
UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
switch ([segmentedControl selectedSegmentIndex]) {
case 0:
{
//NSSortDescriptor *ascSorter = [[NSSortDescriptor alloc ] initWithKey:@"name" ascending:YES];
NSSortDescriptor *ascSorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[self.events sortUsingDescriptors:[NSArray arrayWithObject:ascSorter]];
[self.tableView reloadData];
break;
}
case 1:
{
//NSSortDescriptor *ascSorter = [[NSSortDescriptor alloc ] initWithKey:@"name" ascending:YES];
NSSortDescriptor *descSorter = [[NSSortDescriptor alloc] initWithKey:@"location" ascending:YES];
//[self.events sortUsingDescriptors:[NSArray arrayWithObject:descSorter]];
[self.distances sortUsingDescriptors:[NSArray arrayWithObject:descSorter]];
[self.tableView reloadData];
break;
}
break;
default:
break;
}
}
我现在需要的是一旦用户选项卡 UISegment,表格视图应该根据距离进行排序