【问题标题】:Adding an image to a custom cell subview将图像添加到自定义单元格子视图
【发布时间】:2011-10-30 18:00:14
【问题描述】:

cellForRowAtIndexPath:

  CGRect nameValueRect = CGRectMake(80, 5, 200, 15);
            UILabel *nameValue = [[UILabel alloc] initWithFrame:
                                  nameValueRect];
            nameValue.tag = kNameValueTag;
            [cell.contentView addSubview:nameValue];
            [nameValue release];

...

 NSUInteger row = [indexPath row];
    NSDictionary *rowData = [self.computers objectAtIndex:row];
    UILabel *name = (UILabel *)[cell.contentView viewWithTag:
                                kNameValueTag];
    name.text = [rowData objectForKey:@"Name"];

此代码来自我正在使用的教程,该教程在单元格中创建了一个子视图以添加一些文本。

但是,我想做的是放置一个图像,而不是添加文本。

我试过 UIImageView *posterValue = [[UIImageView alloc] initWith... 哦,UIImageView 没有 initWithFrame。

也许,有人可以解释图像的过程。我什至需要为 UIImageView 设置帧大小吗?我需要定位它。

编辑:

我的新代码:

UIImageView *posterValue = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,105,175)];
        posterValue.tag = kPosterValueTag;
        [cell.contentView addSubView:posterValue];
        [posterValue release];

addSubView 不适用于 UIImageView。说 UIView 可能没有响应 addSubView

【问题讨论】:

  • 等等! UIImageView 有 initWithFrame !我的错。我想这解决了一切?
  • 大声笑,正要说“嗯,UIImageView 继承自 UIView,所以是的,有一个 initWithFrame”
  • 是的,正确显示视图需要框架。
  • 你也可以使用 initWithImage:(UIImage *)。它使框架具有您图像的大小。
  • 我猜 initWithImage 会让我跳过标记步骤?

标签: iphone objective-c ios cocoa-touch


【解决方案1】:

这是 addSubview 而不是 addSubView - 大小写很重要。

【讨论】: