Фон UITableViewCell повторяется, если ячейка прокручивается за пределы экрана - PullRequest
1 голос
/ 04 августа 2010

Я хочу применить специальный фон к первой ячейке в моем UITableView: я применяю bg в:

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

Вот как он применяется:

if (indexPath.row == 1) {
            cell.contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"top-message-bg.png"]];
        }

Проблема в том, что когда эта ячейка прокручивается за пределы экрана, новая ячейка будет иметь indexPath.row == 1. Как я могу убедиться, что только эта ячейка имеет этот фон?

ОБНОВЛЕНИЕ: Вот полный метод

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

   // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    STVCell *cell = (STVCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (indexPath.row == 0) {
        if(mainVideoCell == nil)
        {
            mainVideoCell = [[MainVideoCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"MainVideoCell"];
            mainVideoCell.contentView.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1.0];
        }

        // Configure the cell...
        STVideo *mySTVideo;
        mySTVideo = [items objectAtIndex:indexPath.row];

        mainVideoCell.videoTitle.text = mySTVideo.video_title;

        /*NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
        [formatter setDateStyle:NSDateFormatterShortStyle];
        [formatter setTimeStyle:NSDateFormatterNoStyle];
        NSString *result = [formatter stringFromDate:[NSDate date]];
        [formatter release];*/

        mainVideoCell.dateLabel.text = [Utils toShortTimeIntervalStringFromStockTwits:mySTVideo.publish_on]; //result; //[mySTVideo.publish_on substringToIndex:10];//[Utils toShortTimeIntervalStringFromStockTwits:mySTVideo.publish_on];
        mainVideoCell.videoDescription.text = mySTVideo.description;
        mainVideoCell.authorLabel.text = [NSString stringWithFormat:@"with %@", mySTVideo.author];
        [mainVideoCell.videoThumbnail loadImageFromURL:[NSURL URLWithString:mySTVideo.thumbnail_url]];
        NSLog(@"Description:%@",mySTVideo.description);

        return mainVideoCell;
    } 
    else {
        if (cell == nil) {
            //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
            cell = [[[STVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

        // Configure the cell...
        STVideo *mySTVideo;
        mySTVideo = [items objectAtIndex:indexPath.row];

        cell.videoTitle.text = mySTVideo.video_title;

        /*NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
        [formatter setDateStyle:NSDateFormatterShortStyle];
        [formatter setTimeStyle:NSDateFormatterNoStyle];
        NSString *result = [formatter stringFromDate:[NSDate date]];
        [formatter release];*/

        cell.dateLabel.text = [Utils toShortTimeIntervalStringFromStockTwits:mySTVideo.publish_on];//result; //[mySTVideo.publish_on substringToIndex:10];//[Utils toShortTimeIntervalStringFromStockTwits:mySTVideo.publish_on];
        cell.videoDescription.text = mySTVideo.description;
        cell.authorLabel.text = [NSString stringWithFormat:@"with %@", mySTVideo.author];
        [cell.videoThumbnail loadImageFromURL:[NSURL URLWithString:mySTVideo.thumbnail_url]];

        if (indexPath.row == 1) {
            cell.contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"top-message-bg.png"]];
        }
        else {
            UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
            imageView.image = [[UIImage imageNamed:@"message-bg.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:20];//[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"message-bg.png"]];
            [imageView setOpaque:YES];
            [cell setBackgroundView:imageView];
            [imageView release];
        }


        return cell;        
    }
}

Ответы [ 2 ]

0 голосов
/ 04 августа 2010

Похоже, что-то не так с тем, как вы используете свои клетки. Проблема не в том, что indexPath.row равен единице, а в том, что ячейка, которую вы создали для строки row = 1, используется повторно. Возможно, вам следует добавить еще условие:

if (indexPath.row == 1) {
        cell.contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"top-message-bg.png"]];
    }
else {
    cell.contentView.backgroundColor = [UIColor whiteColor];
}
0 голосов
/ 04 августа 2010

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

if (indexPath.row == 1) {
            cell.contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"top-message-bg.png"]];
}
else
{
     cell.contentView.backgroundColor = // whatever normal background is
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...