Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

iphone - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...