views:

279

answers:

3

I would want to create a custom tableviewcell which should have a different appearance than the default implementation. For this I subclassed the tableviewcell and want to add a label, textbox and a background image. Only the background image seems not to appear. Maybe I'm completely on the wrong track here and maybe subclassing a UItableViewCell is a bad idea after all, is there any reason why that would be the case and is there a better way?

Anyhow this is what I tried, in the subclass's initWithStyle I put the following:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self == nil)
    { 
        return nil;
    }

     UIImage *rowBackground;

     backRowImage = [UIImage imageNamed:@"backRow.png"];
     ((UIImageView *)self.backgroundView).image = backRowImage;

 }

What am I doing wrong here? Should I set the background image in the drawRect method as well?

A: 

I've noticed that using initWithStyle, depending on the style you use, will sometimes prevent you from modifying certain properties of the default UILabels in the cell such as the frame or text alignment. You might want to simply override a different init method for the cell and then manually add new UILabels. This is what I do for any drastically customized UITableViewCell subclasses.

mjdth
A: 

According to the header file, the backgroundView defaults to nil for plain-style tables. You should try creating your own UIImageView and sticking it in there.

Ben Gottlieb
A: 

When I subclass UITableViewCell, I override the layoutSubviews method, and use CGRects to place my subViews inside the contentView of the cell, like so:

First, in your initWithFrame method:

-(id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
        //bgImageView is declared in the header as UIImageView *bgHeader;
        bgImageView = [[UIImageView alloc] init];
        bgImageView.image = [UIImage imageNamed:@"YourFileName.png"];

        //add the subView to the cell
        [self.contentView addSubview:bgImageView];
        //be sure to release bgImageView in the dealloc method!
    }
    return self;
}

Then you Override layoutSubviews, like So:

-(void)layoutSubviews {
    [super layoutSubviews];
    CGRect imageRectangle = CGRectMake(0.0f,0.0f,320.0f,44.0f); //cells are 44 px high
    bgImageView.frame = imageRectangle;
}

Hope this works for you.

JustinXXVII