Search code examples
iphoneuitableviewuiimageviewuiimageuiinterfaceorientation

Why does this UIImage disappear from UITableViewCell when rotating to landscape?


I'm trying to set up a UITableViewCell that can have an image in the upper right corner.

I have it working for portrait mode, but when I rotate to landscape, the image disappears.

Here's the code:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        UIImage *cornerImage = [UIImage imageNamed:@"star_corner.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.bounds.size.width - cornerImage.size.width,
                                                                               0,
                                                                               cornerImage.size.width,
                                                                               cornerImage.size.height)];
        imageView.tag = kCornerImageViewTag;
        [cell.contentView addSubview:imageView];
        [imageView release];
    }

    UIImageView *theView = (UIImageView *)[cell.contentView viewWithTag:kCornerImageViewTag];
    [theView setImage: [UIImage imageNamed:@"star_corner.png"]];

    cell.textLabel.text = @"the text label";
    return cell;
}

Interestingly, if I comment out the "cell.textLabel.text =" line, the image does show in landscape... although it doesn't shift over to the far right.

If there's anything else I'm doing wrong here, please let me know.

Thanks in advance for any assistance.


Solution

  • I figured this out. The solution was to create two UIImageView's... one for the star corner image, and one for the cell background image.

    I added the star corner UIImageView as a subview to the background image UIImageView, then assigned that to cell.backgroundView.

    The star UIImageView positions itself correctly by use of:

    starImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    

    And since the whole thing is assigned to the cell.backgroundView (instead of cell.contentView), it isn't affected by the cell's delete button or reordering controls.