简体   繁体   中英

Customizing an UITableViewCell subclass

I would want to create a custom UITableViewCell which should have a different appearance than the default implementation. For this I subclassed the UITableViewCell 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?

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.

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.

I've noticed that using initWithStyle , depending on the style you use, will sometimes prevent you from modifying certain properties of the default UILabel 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 UILabel . This is what I do for any drastically customized UITableViewCell subclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM