UITableView повторяющиеся ячейки при прокрутке - PullRequest
2 голосов
/ 14 августа 2011

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

Вот код, который я использую. Если что-то нужно, дайте мне знать:

.h

@interface HomeViewController : UITableViewController {


    int numberOfRows;

    NSArray *allVaults;

}

@property (nonatomic, assign) int numberOfRows;
@property (nonatomic, retain) NSArray *allVaults;

@end

.m

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
NSString *vaultsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Vaults"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    self.allVaults = [fileManager contentsOfDirectoryAtPath:vaultsPath error:nil];

numberOfRows = [self.allVaults count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

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


        NSString *vaultsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Vaults"];

        NSString *dictionaryPath = [NSString stringWithFormat:@"%@/%@",
                                    vaultsPath,
                                    [self.allVaults objectAtIndex:indexPath.row]];

    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];

        cell.backgroundView = [AHCellCreation backgroundView];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.selectedBackgroundView = [AHCellCreation selectedBackgroundView];
    cell = [AHCellCreation createCellWithDictionary:dictionary Cell:cell];
    }
    return cell;
}

Любая помощь приветствуется!

РЕДАКТИРОВАТЬ 1: Изображение, показывающее, что происходит, когда я перемещаю большую часть кода за пределы (ячейка == ноль) оператора if:

До: enter image description here

После: enter image description here

РЕДАКТИРОВАТЬ 2:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 82;
}

Ответы [ 2 ]

7 голосов
/ 14 августа 2011

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

    AHCell *cell = (AHCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        // create a new cell if there isn't one available to recycle
        // cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell = [AHCell blankCell];

    }

    // set the contents of the cell (whether it's a new one OR a recycled one)
    NSString *vaultsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Vaults"];

    NSString *dictionaryPath = [NSString stringWithFormat:@"%@/%@",
                                vaultsPath,
                                [self.allVaults objectAtIndex:indexPath.row]];

    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];

    cell.backgroundView = [AHCellCreation backgroundView];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.selectedBackgroundView = [AHCellCreation selectedBackgroundView];
    // cell = [AHCellCreation createCellWithDictionary:dictionary Cell:cell];
    [cell populateAHCellWithDictionary: dictionary];
    return cell;
    }

Обновление Обновленный код для решения второй проблемы.Переработайте AHCell так, чтобы метод класса, например blankCell , возвращал новую ячейку с настроенными подпредставлениями и методом экземпляра, например, populateAHCellWithDictionary: устанавливает содержимое.

2 голосов
/ 14 августа 2011

В этом случае AHCellCreation класс должен добавить подпредставления в ячейку, а затем установить текст за один раз?Вам нужно расположить ячейку внутри оператора if (добавить подпредставления, UILabels, UIImageView и т. Д., Установить их фреймы и т. Д.).И установите содержимое вне оператора if.

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

Когда вы прокручиваете исчезающие ячейки внизот верхней части экрана используются повторно, а внизу ставятся.Это означает, что у вас есть 100 строк, он не будет создавать 100 ячеек (он только создает количество ячеек, которые могут быть видны на экране за раз, и использует их повторно), так как это будет занимать много памяти, ипрокрутка не будет такой гладкой.

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