iphone - 自定义 UITableViewCell 子类

标签 iphone objective-c uitableview

我想创建一个自定义的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/

相关文章:

iphone - 创建一个随机事实应用程序

iPhone硬件功能: magnetometer and gyro

IOS 7 状态栏一直出现

ios - [可能重复]:体系结构i386的 undefined symbol :

iphone - 什么是-[NSString sizeWithFont :forWidth:lineBreakMode:] good for?

ios - 是否可以控制 UITableView 的速度和滚动

iphone - 根据应用设置而不是设备设置,在 UIDatepicker 中以 12 小时和 24 小时格式显示时间

objective-c - 以编程方式共享文件夹

ios - 确定单元格是否在屏幕上并执行功能

iOS - 禁用 UITableViewCell 的向右或向左滑动