【问题标题】:Unable to subclass UITableViewCell无法继承 UITableViewCell
【发布时间】:2011-10-04 05:20:53
【问题描述】:

我创建了一个 UITableViewCell 子类,如下所示。我所做的只是将标签添加到单元格的内容视图并设置其文本。

#import <UIKit/UIKit.h>
@interface CustomTableViewCell : UITableViewCell {
}
@end

#import "CustomTableViewCell.h" 
@implementation CustomTableViewCell

@synthesize horizontalTableView;

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {

        UIView *myContentView = self.contentView;

        UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
        l.text = @"Hi";

        [myContentView addSubview:l];

        [l release];
    }
    return self;
}

现在我以这种方式在表格视图中使用这个自定义单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"MyCell";

    CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, 50, 300) reuseIdentifier:cellIdentifier] autorelease];
    }
     return cell;
}

但是标签没有显示在我的表格视图中。我错过了什么?

【问题讨论】:

  • 在内部使用 NSlog 语句并检查控制是否转到 init 方法。

标签: objective-c ios uitableview


【解决方案1】:

initWithFrame:reuseIdentifier:已弃用,UITableViewCell 的指定初始化程序是 initWithStyle:reuseIdentifier:。可能当您使用当前方法时,contentView 未创建,因此您将标签添加到nil

更重要的是,你甚至没有调用你被覆盖的方法——你已经覆盖了普通的旧 initWithFrame:

【讨论】:

  • 一切都连接好了,并且调用了 cellForRowAtIndexPath。只是没有显示带有标签的自定义单元格!
  • 这个答案是正确的。您需要实现- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 而不是- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 2013-07-13
  • 2023-03-07
  • 2012-08-30
  • 2014-11-10
  • 1970-01-01
  • 2017-01-01
相关资源
最近更新 更多