我想创建一个自定义的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
方法中设置背景图像?
最佳答案
当我子类化 UITableViewCell
时,我重写 layoutSubviews
方法,并使用 CGRects 将我的 subview 放置在单元格的 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;
}
希望这对您有用。
关于iphone - 自定义 UITableViewCell 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2366802/