Search code examples
ios5uitableviewuiimageviewuilabel

Adding UILabel to UIImageView in CellForRow


I have a customCell in StoryBoard "CategoryCell", I have UIImageView with the cell which is also part of the cell also tied up in StoryBoard. The UIImageView is filled with a plain yellow color. I intend to add a label to this plain yellow image, the label varies depending on the cell.

The code below works fine initially, but when I scroll the the tableView, I see label in the image getting messed up, it's like its trying to write new text in top of the text. I figured it's hitting cellForRow again and it's adding new label, How can I make it not create new label on top of old one?

- (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;
 }

Solution

  • You could give the label a tag and use that to check to see if it exists before creating it again :

    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;
    

    Though if it gets any more complicated I might look at subclassing UITableViewCell and using a xib to instantiate the label.