2010-03-02 57 views
2

我想创建一个自定义UITableViewCell它应该有一个不同于默认实现的外观。为此我分类了UITableViewCell并且想要添加标签,文本框和背景图片。只有背景图像似乎不会出现。 也许我完全在这里错误的轨道上,也许子类化UITableViewCell毕竟是一个坏主意,是否有任何理由为什么会是这种情况,有没有更好的办法?自定义一个UITableViewCell子类

总之这是我尝试过,在子类中的initWithStyle我把以下内容:

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

} 

我在做什么错在这里?我应该在drawRect方法中设置背景图像吗?

回答

1

根据头文件,backgroundView对于普通样式表默认为nil。你应该尝试创建你自己的UIImageView并将其粘贴在那里。

0

我注意到,使用initWithStyle,这取决于你使用的样式,有时会阻止您修改单元格中的默认UILabel的某些性能,如框架或文本对齐方式。您可能只想覆盖单元格的其他init方法,然后手动添加新的UILabel。这是我为任何大量定制的UITableViewCell子类所做的。

4

当我继承UITableViewCell,我重写layoutSubviews方法,并使用CGRects把我的子视图细胞的contentView里面,像这样:

首先,在你initWithFrame方法:

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

然后你重写layoutSubviews,就像这样:

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

希望这对你的作品。