2010-04-15 4 views
1

ЭтоПроблема реализации UITableView, что позволяет множественный выбор строк

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

if (cell.accessoryType == UITableViewCellAccessoryNone) { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 
else { 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 

[tableView deselectRowAtIndexPath:indexPath animated:YES]; 

}

... изменяет «accessoryType» каждой 6-й ячейки, а не просто в выбранной строке. Что мне не хватает?

Благодаря

ОБНОВЛЕНО: Вот код создания ячейки ...

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

    static NSString *TC = @"TC"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TC]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PlayerTableViewCell] autorelease]; 
    } 

    NSUInteger row = [indexPath row]; 
    cell.textLabel.text = [NSString stringWithFormat:@"Person %d", row+1]; 

    return cell; 
} 

МОЕ РЕШЕНИЕ на основе отмеченная ответ ниже ...

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

    // EVERY row gets its one Identifier 
    NSString *TC = [NSString stringWithFormat: @"TC%d", indexPath.row]; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TC]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TC] autorelease]; 
    } 

    NSUInteger row = [indexPath row]; 
    cell.textLabel.text = [NSString stringWithFormat:@"Person %d", row+1]; 

    return cell; 
} 

Если лучше, я все уши. Было бы неплохо, если бы мы могли просто изменить SPECICIC Cell в соответствии с NSIndexPath, переданным когда-нибудь (по крайней мере, это кажется мне намного более интуитивным).

ответ

0

Да, только что понял. Это те же самые ячейки (ниже приведены журналы NSLog (@ "% d% @", строка, ячейка)).

2010-04-15 12:43:40.722 ...[37343:207] 0 <MyListCell: 0x124bee0; baseClass = UITableViewCell; frame = (0 0; 320 44); autoresize = RM+TM; layer = <CALayer: 0x124c3a0>> 

2010-04-15 12:43:47.827 ...[37343:207] 10 <MyListCell: 0x124bee0; baseClass = UITableViewCell; frame = (0 31; 340 44); autoresize = W; layer = <CALayer: 0x124c3a0>> 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: PlayerTableViewCell]; 

dequeueReusableCellWithIdentifier использует уже создали ячейку, если предыдущий один из экрана.

Итак, вы должны избегать использования «dequeueReusableCellWithIdentifier» - создать словарь NSIndexPath -> UITableViewCell и использовать его вместо dequeueReusableCellWithIdentifier.

ДОБАВЛЕНО: Вы также можете проверить, если существует (ROWNUMBER + 1) в массиве winningNumbers и заменить аксессуар в Tableview: cellForRowAtIndexPath: метод. Это тоже должно работать

+1

Разве это не против лучшей практики? И может ли это начало иметь некоторые отрицательные последствия, связанные с ростом числа строк? – wgpubs

+0

Хорошо, еще один способ: проверить, существует ли (rowNumber + 1) в массиве выигрышаNumbers и заменить аксессуар в методе cellForRowAtIndexPath. Это тоже должно работать. – kovpas

1

Я получил его для работы, используя настройку типа аксессуара в cellForRowAtIndexPath на основе переменной, которая отслеживает выбранную строку. Затем в didSelectRowAtIndexPath я просто снижу выделение строки, обновляю переменную и перезагружаю таблицу.

КОД ОБРАЗЦА:

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

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row]; 

    if ([_cells indexOfObjectIdenticalTo:_selectedCell] == indexPath.row) { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } else { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    [tableView deselectRowAtIndexPath:indexPath animated:NO]; 

    _selectedCell = [_cells objectAtIndex:indexPath.row]; 
    [tableView reloadData]; 
}