【问题标题】:Customizing an UITableViewCell subclass自定义 UITableViewCell 子类
【发布时间】:2010-03-02 21:12:28
【问题描述】:

我想创建一个自定义的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 方法中设置背景图片吗?

【问题讨论】:

    标签: iphone objective-c uitableview


    【解决方案1】:

    当我继承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;
    }
    

    希望这对你有用。

    【讨论】:

      【解决方案2】:

      根据头文件,对于plain-style表格,backgroundView默认为nil。您应该尝试创建自己的 UIImageView 并将其粘贴在其中。

      【讨论】:

        【解决方案3】:

        我注意到使用initWithStyle,根据您使用的样式,有时会阻止您修改单元格中默认UILabel 的某些属性,例如框架或文本对齐方式。您可能想简单地覆盖单元格的不同初始化方法,然后手动添加新的UILabel。这就是我为任何彻底定制的UITableViewCell 子类所做的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多