UITableView прокрутка и перерисовка проблема - PullRequest
1 голос
/ 04 ноября 2011

Я знаю, что если у меня есть несколько изображений и подпредставлений, добавленных в настраиваемую ячейку, я должен повторно использовать эту ячейку, чтобы пользовательский элемент управления не отображался в других ячейках, но здесь у меня есть другая проблема.Я просто хочу иметь ImageView в первой ячейке первого раздела, поэтому я использовал условие IndexPath.Section == 0 и IndexPath.Row == 0 в следующем коде, но проблема в том, что когда я прокручиваю таблицу, другая ячейка будет соответствовать этому условию имой код также создаст изображение в этой ячейке.Я попытался пометить его и использовать такой же помеченный cellView, но это тоже не помогло.Проблема с ячейкой заключается в отключении взаимодействия с пользователем для нескольких ячеек.В конце концов после прокрутки он отключает взаимодействие с пользователем для всех ячеек.Есть ли способ решить эту проблему?

Спасибо.

- (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];
}

if(indexPath.section == 0 && indexPath.row == 0) {
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me.jpg"]] autorelease];
    UIView *cellView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,320,132)] autorelease];
    [imageView setFrame: CGRectMake(10, 10, 54, 54)];
    [cellView addSubview:imageView];
    cell.backgroundView = cellView;

    return cell;
} else if(indexPath.row == 0) {
    NSString * title = [NSString string];
    switch (indexPath.section) {
        case 1:
            title = @"Friends";
            break;
        case 2:
            title = @"Accounts";
            break;
        case 3:
            title = @"Stats";
            break;
        default:
            title = nil;
            break;
    }
    cell.textLabel.text = title;
    cell.userInteractionEnabled = NO;
    return cell;
}

cell.textLabel.text = @"Test";
return cell;
}

[решено] Правильный код:

- (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];

if(indexPath.section == 0 && indexPath.row == 0) {
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me.jpg"]] autorelease];
    cell.imageView.image = imageView.image;
    cell.textLabel.text = nil;
    cell.textLabel.textColor = [UIColor clearColor];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.userInteractionEnabled = YES;
    return cell;
} else if(indexPath.row == 0) {
    NSString * title = [NSString string];
    switch (indexPath.section) {
        case 1:
            title = @"Friends";
            break;
        case 2:
            title = @"Accounts";
            break;
        case 3:
            title = @"Stats";
            break;
        default:
            title = nil;
            break;
    }

    cell.imageView.image = nil;
    cell.textLabel.text = title;
    cell.textLabel.textColor = [UIColor redColor];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.userInteractionEnabled = NO;

    return cell;
}


cell.imageView.image = nil;
cell.textLabel.text = [cellItems objectAtIndex:(rows+indexPath.row-1)];
cell.textLabel.textColor = [UIColor blueColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.userInteractionEnabled = YES;
return cell;
}

[УЛУЧШЕННЫЙ КОД]

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

static NSString *NormalCellIdentifier = @"NormalCell";
static NSString *TitleCellIdentifier = @"TitleCell";
NSString *neededCellType;

if(indexPath.section == 0 && indexPath.row == 0) {
    neededCellType = TitleCellIdentifier;
} else {
    neededCellType = NormalCellIdentifier;
}

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:neededCellType];

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

    //Only add content to cell if it is new
    if([neededCellType isEqualToString: TitleCellIdentifier]) {
        UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me.jpg"]] autorelease];
        cell.imageView.image = imageView.image;
    }
}

if([neededCellType isEqualToString: NormalCellIdentifier]) {
    NSString * title;
    if(indexPath.row == 0) {
        switch (indexPath.section) {
            case 1:
                title = @"Friends";
                break;
            case 2:
                title = @"Accounts";
                break;
            case 3:
                title = @"Stats";
                break;
            default:
                title = nil;
                break;
        }
        cell.textLabel.text = title;
        cell.textLabel.textColor = [UIColor redColor];
        cell.userInteractionEnabled = NO;
    } else {

        cell.userInteractionEnabled = YES;
        cell.textLabel.textColor = [UIColor blueColor];
        cell.textLabel.text = @"Test";
    }
}

return cell; 
}

Ответы [ 2 ]

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

Я думаю, что ваша проблема в том, что повторное использование ячеек делает так, чтобы ячейки, которые не создаются как новые ячейки, имели набор свойств, которые вы должны переопределить.Например, попробуйте присвоить cell.userInteractionEnabled = YES всем остальным случаям и посмотрите, каков будет результат.

0 голосов
/ 04 ноября 2011

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

Вот два решения:

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {</p>

<p>static NSString *NormalCellIdentifier = @"NormalCell";
static NSString *TitleCellIdentifier = @"TitleCell";
NSString *neededCellType;</p>

<p>if(indexPath.section == 0 && indexPath.row == 0) {
     neededCellType = TitleCellIdentifier;
} else {
     neededCellType = NormalCellIdentifier;
}</p>

<p>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:neededCellType];</p>

<p>if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:neededCellType] autorelease];</p>

<p>//Only add content to cell if it is new
   if([neededCellType isEqualToString: TitleCellIdentifier]) {
       UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me.jpg"]] autorelease];
    UIView *cellView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,320,132)] autorelease];
    [imageView setFrame: CGRectMake(10, 10, 54, 54)];
    [cellView addSubview:imageView];
    cell.backgroundView = cellView;
   }
}</p>

<p>if([neededCellType isEqualToString: NormalCellIdentifier]) {
NSString * title;
 if(indexPath.row == 0) {</p>

<pre><code>switch (indexPath.section) {
    case 1:
        title = @"Friends";
        break;
    case 2:
        title = @"Accounts";
        break;
    case 3:
        title = @"Stats";
        break;
    default:
        title = nil;
        break;
}
cell.textLabel.text = title;
cell.userInteractionEnabled = NO;
</code>

}

else { cell.textLabel.text = @"Test"; return cell; } } }

(эти последние несколько строк выпали из поля кода).Это должно сделать это.

...