UITableViewCell используется повторно, но я не могу понять, почему? - PullRequest
0 голосов
/ 16 ноября 2011

Я получил таблицу, загруженную из массива, и по какой-то причине он повторно использует ячейку, но загружает ту же информацию вниз в таблицу, во второй раз.

http://screencast.com/t/Ig8bcqSpLzp

Видео выше должно дать вам представление о том, что я имею в виду.

Это мой код для загрузки ячейки:

  - (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];
    }
        accessicon *current =[arryAccess objectAtIndex:indexPath.row] ;
        cell.textLabel.text = current.text;
        cell.imageView.image = [UIImage imageNamed: current.iconPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        mySwitch *switchView = [[mySwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchView;
        switchView.myValue = current.iconValue;

        if(totalIconValue & current.iconValue) {
            [switchView setOn: YES animated:NO];
        } else {
            [switchView setOn: NO animated:NO];

        }

        [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
        [switchView release];


        return cell;


}

Любая помощь будет оцененаесли я прокручиваю вверх и вниз, он выбирает их сам?

смотрите видео здесь: http://screencast.com/t/a9N1qbws

Том

Ответы [ 3 ]

3 голосов
/ 16 ноября 2011

Этот код:

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

в корне неверно. Следует читать:

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

И затем, все, что специфично для строки, должно быть за пределами этого if оператора.

Шаблон для этого, как правило, должен быть:

  • снять многоразовую ячейку
  • если вы его не получили:
    • выделить новую ячейку
    • выполнить общую настройку ячейки, то есть настройку, которая применяется ко всем ячейкам
  • установить ячейку для конкретной строки и вернуть ее.

Надеюсь, это поможет.

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

Вы не используете свои клетки повторно.И вы заполняете ячейки только тогда, когда инициализация не удалась.Попробуйте этот код:

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

accessicon *current =[arryAccess objectAtIndex:indexPath.row] ;
cell.textLabel.text = current.text;
cell.imageView.image = [UIImage imageNamed: current.iconPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
mySwitch *switchView = [[mySwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
switchView.myValue = current.iconValue;

if(totalIconValue & current.iconValue) {
    [switchView setOn: YES animated:YES];
} else {
    [switchView setOn: NO animated:YES];

}

[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchView release];

Или разработайте под ios5 и избавьтесь от alloc и init.

1 голос
/ 16 ноября 2011

Вы постоянно создаете новые строки, а не используете старые.

Переместить линию

    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

внутри блока if, end переместить все остальное, что есть в блоке if вне его, кроме строк

mySwitch *switchView = [[mySwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;

Вам нужно создать переключатель только один раз для строки, когда она инициализируется (это означает, что в операторе if). Я предлагаю вам создать его и назначить ему тег, чтобы вы могли получить к нему доступ позже по его тегу. Ваш код теперь создает новый переключатель каждый раз, когда используется ячейка, это может быть причиной того, что переключатели ведут себя таким образом.

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