如何在iPhone sdk的uitableview中避免标签文本重新加载?

时间:2012-04-05 10:45:35

标签: iphone uitableview uilabel

我的网络服务中有一些产品。我从中获取产品名称并使用标签文本在我的tableview中显示它。我明白了。现在我的问题是,当我在tableview中选择一些产品时,我的标签会重新加载并覆盖我现有的标签文本,即使我的didselectrowatindexpath为空。我用过这个,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
    bookName = [[UILabel alloc]initWithFrame:CGRectMake(100, 3, 180, 25)];
    NSString *text = [NSString stringWithFormat:@"%@",[[stories objectAtIndex:indexPath.row]    objectForKey: @"product_name"]];
    bookName.text = text;
    bookName.textAlignment = UITextAlignmentCenter;
    bookName.lineBreakMode = UILineBreakModeWordWrap;
    [bookName setTextColor:[UIColor blackColor]];

    CGSize expectedLabelSize = [text sizeWithFont:bookName.font constrainedToSize:bookName.frame.size lineBreakMode:UILineBreakModeWordWrap];
    CGRect newFrame = bookName.frame;
    newFrame.size.height = expectedLabelSize.height;
    bookName.frame = newFrame;
    bookName.numberOfLines = 0;
    [bookName sizeToFit];
    [cell.contentView addSubview:bookName];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{

}

2 个答案:

答案 0 :(得分:3)

在UILabel代码上方添加以下代码。这可能会对您有所帮助。

for(UIView *view in cell.contentView.subviews) 
{
    [view removeFromSuperview]; 
}

答案 1 :(得分:2)

使用以下cellForRowAtIndexPath方法。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    }

    UILabel *bookName = (UILabel*)[cell.contentView viewWithTag:1001];
    if( !bookName )
    {
        bookName = [[UILabel alloc]initWithFrame:CGRectMake(100, 3, 180, 25)];
        [cell.contentView addSubview:bookName];
        bookName.tag = 1001;
        bookName.numberOfLines = 0;
        bookName.textAlignment = UITextAlignmentCenter;
        bookName.lineBreakMode = UILineBreakModeWordWrap;
        [bookName setTextColor:[UIColor blackColor]];
    }

    NSString *text = [NSString stringWithFormat:@"%@",[[stories objectAtIndex:indexPath.row]    objectForKey: @"product_name"]];
    bookName.text = text;

    CGSize expectedLabelSize = [text sizeWithFont:bookName.font constrainedToSize:bookName.frame.size lineBreakMode:UILineBreakModeWordWrap];
    CGRect newFrame = bookName.frame;
    newFrame.size.height = expectedLabelSize.height;
    bookName.frame = newFrame;
    [bookName sizeToFit];
}