Удаление нескольких (еще не загруженных) строк в UITableView - PullRequest
0 голосов
/ 23 июля 2010

У меня возникли некоторые проблемы при попытке удалить строки, которые не были загружены (или не видны) из UITableview.

Моя настройка следующая -

В табличном представлении есть два раздела, и каждый элемент в разделе 1 связан с несколькими элементами из второго раздела.

Чтобы дать вам пример (Данные на самом деле не связаны с тем, что я пытаюсь сделать, но я верю, что это будет пример, который на самом деле не требует большого объяснения)

Раздел 1

  • BMW
  • Acura
  • Merc

Раздел 2

  • 328i
  • 335i
  • RX
  • LX
  • TX
  • C300
  • C550

Моя внутренняя модель выглядит примерно так -

NSMutableArray Cars[]
NSMutableArray Models[]

cars[0] = "BMW"
cars[1] = "Acura"
cars[2] = "Merc"

Каждый элемент в Моделях [] является вектором, а их составляющие перечислены ниже

Models = [ ["328i", "335i"], ["RX", "LX", "TX"], ["C300", "C550"] ];

Так что для функциональности я пытаюсь построить. Если пользователь нажимает кнопку удаления и пытается удалить BMW, приложение должно удалить запись для BMW из раздела 1 и записи для 328i и 335i во втором разделе. Однако пользователь может самостоятельно удалить любую отдельную строку второго раздела.

Может кто-нибудь указать мне, как я могу продолжить это?

Ответы [ 2 ]

1 голос
/ 26 июля 2010

NSMutableArray * Cars = [[NSMutableArray alloc] initWithObjects: @ "BMW", @ "Acura", @ "Merc", ноль];

NSMutableArray *Arr1 = [[NSMutableArray alloc]initWithObjects:@"328i", @"335i",nil];
NSMutableArray *Arr2 = [[NSMutableArray alloc]initWithObjects:@"RX", @"LX", @"TX",nil];
NSMutableArray *Arr3 = [[NSMutableArray alloc]initWithObjects:@"C300", @"C550",nil];

NSMutableArray * Models = [[NSMutableArray alloc] initWithObjects:Arr1,Arr2,Arr3,nil];

При удалении, если вы удаляете BMW, удалите 1-й элемент из массива Models и 1-й элемент из массива Cars и таблицу перезагрузки. т.е.

[Cars removeObjectAtIndex:0];
[Models removeObjectAtIndex:0];
[tableview reload];     //tableview - object of UiTableView
0 голосов
/ 26 июля 2010
- (void)tableView:(UITableView *)tableView 
            commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
            forRowAtIndexPath:(NSIndexPath *)indexPath {
int row = indexPath.row;


if(indexPath.section ==0) {
    // Need to remove both the Car and the Models associated with it.
    // Begin updates. Doesn't commit edits till endUpdates;
    [tableView beginUpdates];

    // Get the indexPaths to be removed.
    // Cars is straight forward.
    NSMutableArray *carsIndexPath = [[NSMutableArray alloc] init];
    NSIndexPath *carsIndexPathObj = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
    [carsIndexPath addObject:carsIndexPathObj];

    // Manually make index paths for models associated with the car.
    NSMutableArray *modelIndexPaths = [self getIndexPaths:indexPath.row];

    // Now remove from model
    [models removeObjectAtIndex:indexPath.row];
    [cars removeObjectAtIndex:indexPath.row];

    // Remove from Table
    [tableView deleteRowsAtIndexPaths:carsIndexPaths withRowAnimation:UITableViewRowAnimationLeft];
    [tableView deleteRowsAtIndexPaths:modelIndexPaths withRowAnimation:UITableViewRowAnimationLeft];

    // Commit updates
    [tableView endUpdates];

    // Reload data.
    [tableView reloadData];

}
}

-(NSMutableArray *) getIndexPaths:(NSInteger) index {   
    NSMutableArray *indexPathArray = [[NSMutableArray alloc] init];
    int offset = 0;
    for (int i=0; i<index; i++) {
        NSMutableArray *tempArr = [models objectAtIndex:i];
        offset += [tempArr count];
    }
    NSMutableArray *currentModels = [models objectAtIndex:index];
    for (int i=0; i<[currentModels count]; i++) {
        NSIndexPath *indexPathTemp = [NSIndexPath indexPathForRow:offset+i inSection:1];
        [indexPathArray addObject:indexPathTemp];
    }   
    return indexPathArray;
}

(Если это вообще имеет смысл)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...