0

我的网络服务中有一些产品。我从中获取产品名称并使用标签文本在我的表格视图中显示它。我明白了。现在我的问题是,当我在我的表格视图中选择一些产品时,我的标签会重新加载并用我现有的标签文本覆盖,即使我的 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 
{

}
4

2 回答 2

3

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

for(UIView *view in cell.contentView.subviews) 
{
    [view removeFromSuperview]; 
}
于 2012-04-05T10:59:57.203 回答
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];
}
于 2012-04-05T11:02:50.917 回答