2010-03-02 58 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; 
} 

希望這對你的作品。