テーブル ビューにイベントを表示するアプリがあります。このテーブルをアルファベット順に並べ替える 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をタブにすると、距離に基づいてテーブルビューをソートする必要があることです