UITableview重叠

时间:2011-01-11 10:32:06

标签: iphone uitableview

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

    static NSString *CellIdentifier = @"Cell";

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

    // Configure the cell.

    Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];
    UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 22)];
    UILabel *myLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 300, 22)];
    UILabel *myLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 300, 22)];
    myLabel1.text=aBook.title;
    myLabel2.text=aBook.description;
    myLabel3.text=aBook.pubDate;

    [cell addSubview:myLabel1];
    [cell addSubview:myLabel2];
    [cell addSubview:myLabel3];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // Set up the cell

    return cell;
}

我有这个代码。它显示在XML文件中。滚动时,文本会重叠。请帮帮我。

1 个答案:

答案 0 :(得分:3)

每次重复使用单元格时,都会向单元格添加标签,因此最终会在一个单元格中将多个标签堆叠在一起。您需要更改的是仅在创建单元格时创建标签:

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

    static NSString *CellIdentifier = @"Cell";

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

        UILabel *myLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 22)];
        UILabel *myLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 300, 22)];
        UILabel *myLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 300, 22)];
        myLabel1.tag = 101;
        myLabel2.tag = 102;
        myLabel3.tag = 103;

        [cell.contentView addSubview:myLabel1];
        [cell.contentView addSubview:myLabel2];
        [cell.contentView addSubview:myLabel3];
        [myLabel1 release];
        [myLabel2 release];
        [myLabel3 release];
    }

    // Configure the cell.

    Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];
    UILabel *myLabel1 = (UILabel*)[cell.contentView viewWithTag:101];
    UILabel *myLabel2 = (UILabel*)[cell.contentView viewWithTag:101];
    UILabel *myLabel3 = (UILabel*)[cell.contentView viewWithTag:101];
    myLabel1.text=aBook.title;
    myLabel2.text=aBook.description;
    myLabel3.text=aBook.pubDate;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // Set up the cell

    return cell;
}

还有两件事需要解决:

  • 在将它们添加到单元格后,不要忘记释放您创建的标签,否则会导致内存泄漏并最终导致内存不足问题(尤其是使用tableview)
  • 将子视图添加到单元格的contentView,而不是直接添加到单元格