Yangrui
Yangrui

Reputation: 1247

Table view cell text overlaps others when tapped multiple times

I created a list of Youtube videos but there are some problems:

- (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 *url = [selectedCellItem.content objectAtIndex:indexPath.row];

    UIWebView *wbView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, ROW_HEIGHT, ROW_HEIGHT)];
    wbView.tag = 1;
    [cell.contentView addSubview:wbView];
    [wbView release];

    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";

    NSString *html = [NSString stringWithFormat:embedHTML,url, ROW_HEIGHT, ROW_HEIGHT];
    UIWebView *thisVideoView = (UIWebView *)[cell.contentView viewWithTag:1];  
    thisVideoView.delegate = self;
    [thisVideoView loadHTMLString:html baseURL:nil];

    CGFloat cellWidth = [UIScreen mainScreen].bounds.size.width-ROW_HEIGHT-5;
    NSString *cellValue = [selectedCellItem.title objectAtIndex:indexPath.row];
    CGRect labelFrame = CGRectMake(ROW_HEIGHT+5, 0.0, cellWidth, ROW_HEIGHT);
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:labelFrame];

    titleLabel.tag = 2;
    titleLabel.text = cellValue;
    titleLabel.font = [UIFont systemFontOfSize:14.0];
    [titleLabel setNumberOfLines:10];
    [cell.contentView addSubview:titleLabel];
    [titleLabel release];

    return cell;
}

At the beginning, my app works just fine. However, when I click one cell multiple times the label starts overlapping with other cell labels. How can I fix this problem?

Upvotes: 0

Views: 1459

Answers (2)

Sr.Richie
Sr.Richie

Reputation: 5740

It's happening because you're creating the titleLabel everytime the function is called. Keep in mind that cell are re-used when table view is scrolled, so basically everytime a cell is used you're re-creating the titleLabel without removing the old one

Upvotes: 2

tobiasbayer
tobiasbayer

Reputation: 10379

Try to set cell.clipsToBounds = YES.

Upvotes: 2

Related Questions