UITableView, загруженный из MutableArray, превращается в список для отметок - PullRequest
0 голосов
/ 08 ноября 2011

У меня есть таблица, которая загружается с изменяемого массива, как указано ниже. Однако мне нужно присвоить каждому элементу массива идентификатор и поставить галочку рядом с элементом. В основном это настройки для нашего поиска, он позволяет пользователям устанавливать приоритеты в зависимости от того, какие флажки установлены. Поэтому я хочу сохранить, какие элементы отмечены в списке или аналогичном.

Вот как загружается массив:

arryTableIconsText =     [[NSMutableArray alloc] init]; 

[arryTableIconsText addObject:@"Facilities for partially sighted or blind people"];
[arryTableIconsText addObject:@"An 'assistance dogs welcome' policy"];
[arryTableIconsText addObject:@"Disabled access facilities for wheelchair users (with assistance)"];
*more items added here*

arryTableIcons = [[NSMutableArray alloc] init];

[arryTableIcons addObject:@"visuallyImpaired_off.png"];
[arryTableIcons addObject:@"guidedogs_off.png"];
[arryTableIcons addObject:@"wheelchairassist_off.png"];
    *more items added here*

А затем загружается в таблицу примерно так:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];

    cell.textLabel.text = [arryTableIconsText objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[arryTableIcons objectAtIndex:indexPath.row]];   

    return cell;
}

Результат следующий:

Icons

Но я не знаю, куда идти отсюда, чтобы преобразовать его в флажок справа от каждой ячейки с сохраненным идентификатором?

Любые советы действительно будут оценены, Том

1 Ответ

2 голосов
/ 08 ноября 2011

Используйте переменную экземпляра NSMutableIndexSet и заполните ее индексом проверяемых ячеек.

Затем в методе cellForRowAtIndexPath установите тип аксессуара для ячейки UITableViewCellAccessoryTypeCheckmark или * 1006.* в зависимости от того, что indexPath.row находится в NSMutableIndexSet or not.

Наконец, когда ячейка коснулась, добавьте indexPath.row в набор индексов, если он не прочитан, или удалите его, если он уже присутствовал, чтобыпереключите состояние соответствующей ячейки, затем вызовите reloadData для tableView.

Я также вижу в вашем коде, что вы не знакомы с механизмом повторного использования UITableViewCells.Вам следует прочитать «Руководство по программированию табличного представления» в документации Apple и узнать, как реализовать cellForRowAtIndexPath более эффективным и реактивным способом (с точки зрения реактивности и объема памяти)


Пример

// Let selectedCellIndexes be an instance variable in your .h of type NSMutableIndexSet*
// Initialize it (probably at the same place you initialise your texts & icons, once for all, probably in your init method
selectedCellIndexes = [[NSMutableIndexSet alloc] init];

Затем для заполнения ячеек:

-(UITableViewCell*)tableView:(UITableView*)tv cellForRowAtIndexPath:(NSIndexPath*)indexPath {
  // Try to recycle and already allocated cell (but not used anymore so we can reuse it)
  UITableViewCell* cell = [tv dequeueCellWithReuseIdentifier:...];
  if (cell == nil) {
    // If we didn't manage to get a reusable (existing) cell to recycle it
    // then allocate a new one and configure its general properties common to all cells
    cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];

    // ... configure stuff that are common to all your cells : lineBreakMode, numberOfLines, font... once for all
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
  }

  // Then here change the stuff that are different between each cell
  // (this code will be executed if the cell has just been allocated as well as if the cell is an old cell being recycled)
  cell.textLabel.text = [arryTableIconsText objectAtIndex:indexPath.row];
  cell.imageView.image = [UIImage imageNamed:[arryTableIcons objectAtIndex:indexPath.row]];
  cell.accessoryType = [selectedCellIndexes containsIndex:indexPath.row] ? UITableViewCellAccessoryTypeCheckmark : UITableViewCellAccessoryTypeNone;

  return cell;
}

И, наконец, для переключения галочек:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  if ([selectedCellIndexes containsIndex:indexPath.row]) {
    [selectedCellIndexes removeIndex:indexPath.row];
  } else {
    [selectedCellIndexes addIndex:indexPath.row];
  }
  [tableView reloadData];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...