将标签放在UITableView中的麻烦

时间:2011-06-12 13:50:55

标签: iphone objective-c

我使用此代码显示UITableView 2段

if(segment.selectedSegmentIndex==0)
    {

        firstSeg=[firsArray objectAtIndex:indexPath.row];

        NSString * celldata = [NSString stringWithFormat:@"%@  %@  %@",firstSeg.a,firstSeg.b,firstSeg.c];

        lbl =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 20) ];

        lbl.text=celldata;
        [cell.contentView addSubview:lbl];   
    }
    else if(segment.selectedSegmentIndex==1) {

        seconSeg=[secondArray objectAtIndex:indexPath.row];

        NSString * celldata = [NSString stringWithFormat:@"%@  %@  %@",secondSeg.a,secondSeg.b,secondSeg.c];

        lbl2 =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 20) ];

        lbl2.text=celldata;
        [cell.contentView addSubview:lbl2];
        }


    return cell;

我的tableView和我的细分可以正常工作,但当我在第二个细分中选择一行时,第一个标签lbllbl2会一起出现。我尝试在第二部分中制作lbl=nillbl=NULL,但它不起作用,你能帮帮我吗?


有了这个 cell.textLabel.text = celldata; 它很完美,但文字太大了,我不能修改它的大小?

2 个答案:

答案 0 :(得分:3)

问题是每次重新加载tableview单元格时都要将标签添加到单元格

尝试仅添加一次标签,并为此标签指定标签

在文件顶部添加:

#define CELL_LABEL_TAG 333

创建单元格时,还要创建标签并将其添加为子视图

UILabel *lbl =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 20) ];
[lbl setTag:CELL_LABEL_TAG];
[cell.contentView addSubview:lbl];

将您的代码更改为:

if(segment.selectedSegmentIndex==0) {

    firstSeg=[firsArray objectAtIndex:indexPath.row];

    NSString * celldata = [NSString stringWithFormat:@"%@  %@  %@",firstSeg.a,firstSeg.b,firstSeg.c];

    lbl =(UILabel *)[cell.contentView viewWithTag:CELL_LABEL_TAG];

    lbl.text=celldata;
}
else if(segment.selectedSegmentIndex==1) {

    seconSeg=[secondArray objectAtIndex:indexPath.row];

    NSString * celldata = [NSString stringWithFormat:@"%@  %@  %@",secondSeg.a,secondSeg.b,secondSeg.c];

    lbl2 =(UILabel *)[cell.contentView viewWithTag:CELL_LABEL_TAG];

    lbl2.text=celldata;
    }


return cell;

答案 1 :(得分:0)

如果您没有多个单元格,请分配新的UITableViewCell对象,而不是重复使用单元格。 这可以解决你的问题。

将标签添加为子视图后释放标签!

相关问题