UITableview dequeueReusableCellWithIdentifier и проблемы с прокруткой - PullRequest
1 голос
/ 04 августа 2011

Итак, у меня есть некоторые проблемы с моим tableview. У меня есть пользовательский label, который я положил в tableview cell, чтобы добавить немного лучшую графику, чем стандартный UItableviewcell. Тем не менее, я столкнулся с моей первой проблемой,

  1. текстовые метки, которые были у меня на cells, менялись при перезаписи и перезаписи друг друга при прокрутке, только когда cells отошел от экрана, а затем вернулся. После некоторых исследований я обнаружил, что, возможно, это как-то связано с dequeueReusableCellWithIdentifier:, поэтому я скорректировал свой код. вот где возникает вторая проблема.

  2. Когда я загружаю table, все на своем месте, выглядит правильно и все. Однако, когда я начинаю опускаться на scroll, я могу добраться до всех своих ячеек, кроме последней, она дойдет до самого низа восьмой ячейки и остановится, но у меня должно быть загружено 9 ячеек.

Меня это смущает, может кто-нибудь дать какой-нибудь код или руководство, чтобы помочь мне?

Спасибо.

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


NSLog(@"Run");
CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *keys = [[appDelegate rowersDataStore] allKeys];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    // Configure the cell...


    label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
    label.font = [UIFont boldSystemFontOfSize:16];
    label.backgroundColor = [UIColor clearColor];
    label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    label.shadowOffset = CGSizeMake(0,1);
    label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];

    switch (indexPath.section) {
        case 0:
            label.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
            label.textAlignment = UITextAlignmentCenter;
            break;
        case 1:

            label.textAlignment = UITextAlignmentLeft;
            UIImage *accessoryImage = [UIImage imageNamed:@"content_arrow.png"];
            UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
            cell.accessoryView = accessoryView;
            [accessoryView release];
            break;
    }



    UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
    UIImage* img = [UIImage imageNamed:@"odd_slice.png"];
    imgView.image = img;
    cell.backgroundView = imgView;
    [imgView release];

    //Selected State
    UIImage *selectionBackground = [UIImage imageNamed:@"row_selected.png"];
    UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
    selectionView.image = selectionBackground;
    cell.selectedBackgroundView = selectionView;
    [selectionView release];
}

switch (indexPath.section) {
    case 0:
        [label setText:@"Click to add new rower"];
        break;
    case 1:
        [label setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:@"Name"]];
        break;
}

//Adds Text
[cell addSubview:label];

return cell;

}

1 Ответ

4 голосов
/ 04 августа 2011

Я вижу несколько вопросов здесь.Во-первых, общая структура этого метода должна быть ...

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

    // Attempt to dequeue the cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // If cell does not exist, create it, otherwise customize existing cell for this row
    if (cell == nil) {
        // Create cell
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        // Configure cell:
        // *** This section should configure the cell to a state independent of 
        //  whatever row or section the cell is in, since it is only executed 
        //  once when the cell is first created.
    }

    // Customize cell:
    // *** This section should customize the cell depending on what row or section 
    //  is passed in indexPath, since this is executed every time this delegate method
    //  is called.

    return cell;
}

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

После создания ячейки (то есть вне оператора if (cell == nil)), вы должны настроить еесвойства в соответствии с тем, как ячейка должна выглядеть для конкретной строки и раздела, содержащихся в indexPath.Поскольку вы хотите получить доступ к своей пользовательской метке в этой части кода, я присвоил ей значение tag, чтобы мы могли получить к нему доступ вне сегмента кода, в котором он был создан, с помощью viewWithTag:.Получив метку, мы можем настроить ее в соответствии с разделом, а также сделать все, что захотим, например, настроить вспомогательный вид.

Я немного изменил / очистил ваш код ниже.Это далеко не самый эффективный или элегантный способ делать то, что вы хотите, но я пытался сохранить как можно больше вашего кода.Я не проверял это, но если вы попробуете это, оно должно работать:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Run");
    CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSArray *keys = [[appDelegate rowersDataStore] allKeys];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // Configure the cell...

        UILabel *label;
        label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 15, cell.bounds.size.width - 10, 30)] autorelease];
        label.font = [UIFont boldSystemFontOfSize:16];
        label.opaque = NO;
        label.backgroundColor = [UIColor clearColor];
        label.shadowColor = [UIColor colorWithWhite:1.0 alpha:0.5];
        label.shadowOffset = CGSizeMake(0,1);
        label.textColor = [UIColor colorWithRed:0x4c/255.0 green:0x4e/255.0 blue:0x48/255.0 alpha:1.0];
        label.tag = 100;
        [cell addSubview:label];
        [label release];

        UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
        UIImage* img = [UIImage imageNamed:@"odd_slice.png"];
        imgView.image = img;
        cell.backgroundView = imgView;
        [imgView release];

        //Selected State
        UIImage *selectionBackground = [UIImage imageNamed:@"row_selected.png"];
        UIImageView *selectionView = [[UIImageView alloc] initWithFrame:cell.frame];
        selectionView.image = selectionBackground;
        cell.selectedBackgroundView = selectionView;
        [selectionView release];
    }

    UILabel *lbl = (UILabel *)[cell viewWithTag:100];
    switch (indexPath.section) {
        case 0:
            cell.accessoryView = nil;

            lbl.frame = CGRectMake(0, 15, cell.bounds.size.width - 10, 30);
            lbl.textAlignment = UITextAlignmentCenter;
            [label setText:@"Click to add new rower"];
            break;
        case 1:
            UIImage *accessoryImage = [UIImage imageNamed:@"content_arrow.png"];
            UIImageView *accessoryView = [[UIImageView alloc] initWithImage:accessoryImage];
            cell.accessoryView = accessoryView;
            [accessoryView release];

            lbl.frame = CGRectMake(20, 15, cell.bounds.size.width - 10, 30);
            lbl.textAlignment = UITextAlignmentLeft;
            [lbl setText:[[[appDelegate rowersDataStore] objectForKey:[keys objectAtIndex:indexPath.row]] objectForKey:@"Name"]];
            break;
    }

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