2013-05-16 57 views
0

我在StoryBoard“CategoryCell”中有一个customCell,我的UIImageView的单元格也是该单元的一部分,也捆绑在StoryBoard中。 UIImageView充满纯黄色。我打算为这个纯黄色的图像添加标签,标签因单元格而异。将UILabel添加到CellForRow中的UIImageView中

下面的代码最初工作正常,但是当我滚动tableView时,我看到图像中的标签变得混乱,就像它试图在文本顶部写入新文本。我认为它再次触及cellForRow,它添加了新标签,我如何使它不会在旧版标签上创建新标签?

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

if([tableView isEqual:wordsTableView]) 
{ 
    CategoryCell *cell = [CategoryTableView dequeueReusableCellWithIdentifier:@"CategoryCellIdentifier" forIndexPath:indexPath]; 
    if(!cell) 
     cell = [[CategoryCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:@"CategoryCellIdentifier"]; 

    NSString *text = [[theCategories objectAtIndex:indexPath.row] uppercaseString]; 

    //Add label now 
    catLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 20)]; 
    catLabel.text = text; 
    [cell.codeImageView addSubview:catLabel]; 

    return cell; 
} 

回答

1

你可以给标签标记,并用它来检查,看它是否再次创建它之前就存在:

UILabel *catLabel = [cell.codeImageView viewWithTag:100]; 
if (nil == catLabel) { 
    catLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 20)]; 
    catLabel.tag = 100; 
    [cell.codeImageView addSubview:catLabel]; 
} 
catLabel.text = text; 

但如果它得到任何比较复杂,我可能看子类的UITableViewCell和使用xib实例化标签。

+0

它的工作原理,谢谢 - 我知道它必须处理标签。 BTW,CategoryCell是UITableViewCell的一个子类。 – IronMan1980