自定义 TableViewCell 中的图像消失了吗?

Image in custom TableViewCell disappeared?

我想自定义我的 TableViewCell,它只填充一张图片。我尝试调整单元格和图像视图的框架大小,但是当我 运行 这个程序时,我无法在屏幕上看到我的图像。

这是我关于客户手机的代码:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {
        [self initLayout];
   }

   return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)initLayout {
    self.imageView.frame = self.contentView.frame;

    [self addSubview:_image];
}

- (void)resizeWithWidth:(NSInteger)width {
    // I want the picture's width equal to the screen's, and the picture's height is 1/3 of its width
    CGRect frame = [self frame];
    frame.size.width = width;
    frame.size.height = width / 3;
    self.frame = frame;
    self.imageView.frame = frame;
}

在我的 TableViewController 中,我以这种方式获取单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   IntroductViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"introductcell" forIndexPath:indexPath];

   // Configure the cell...
   if (cell) {
       cell = [[IntroductViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"introductcell"];
   }


   cell.imageView.contentMode = UIViewContentModeScaleAspectFill;

   if (indexPath.row == 0) {
       cell.imageView.image = [UIImage imageNamed:@"1.jpeg"];
   } else if (indexPath.row == 1) {
       cell.imageView.image = [UIImage imageNamed:@"2.jpeg"];
   }

   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   [cell resizeWithWidth:[UIScreen mainScreen].bounds.size.width];

   return cell;
}

而且,这是我在 运行 我的程序时看到的:

run image

PS:我注意到每个单元格都有一些 space。我怎样才能删除它们?

PS 2:我试图删除该行:cell.selectionStyle = UITableViewCellSelectionStyleNone;在cellForIndex中,我发现当点击第二个单元格时,它显示了图像,但是我在第一个单元格中仍然看不到第一张图像,有什么关系吗?

删除分隔线使用 tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

我看到代码有几个可能的问题,但我不能保证这会在没有更多上下文的情况下解决问题。

1) 您正在使用 - dequeueReusableCellWithIdentifier:forIndexPath: 这要求您调用 registerNib:forCellReuseIdentifier: 或 registerClass:forCellReuseIdentifier:(第一个如果您正在使用界面生成器,第二个如果您仅在代码中定义单元格)。我猜你的情况需要第二个。示例(这在您的 TableViewController 的 viewDidLoad 中是合适的):

[tableView registerClass: [IntroductViewCell class] forCellReuseIdentifier: @"introductcell"];

抱歉,如果我的 Objective-C 有点问题,我在过去一年左右的时间里一直在使用 Swift。如果你已经有了这个但把那部分留在了这个问题之外,那没关系。

2)去掉这个位:

   if (cell) {
       cell = [[IntroductViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"introductcell"];
   }

首先,您可能想要 !cell 在那里(或类似的东西)。您可能不想废弃已经存在的单元格(如果分配了 none,您想要一个新单元格,对吗?如果单元格检索成功则不要重新分配)。其次,一旦你做了 registerClass / 就不再需要它了 dequeueReusableCellWithIdentifier:forIndexPath:组合(特别是,后一种方法将始终 return 一个有效的单元格)。