ios - UIImageView 在表格 View 中的图像左侧有奇怪的空间

标签 ios objective-c uitableview uiimageview

我有一个 UITableView,我以编程方式将其添加到我的 View 中。然后我从 API 加载数据,调整图像大小以适应当前设备的宽度,并相应地调整图像的高度以保持纵横比,然后我使用该高度作为单元格的高度我的表格 View 。

这是一些代码和结果的屏幕截图:

这是调整图像大小的代码:

+ (UIImage*)imageWithImage:(UIImage *)image convertToWidth:(float)width {
    float ratio = image.size.width / width;
    float height = image.size.height / ratio;
    CGSize size = CGSizeMake(width, height);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage * newimage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimage;
}

这是在我的自定义表格 View 单元格的初始化方法中:

 _imgPicture = [[UIImageView alloc] init];
 _imgPicture.contentMode = UIViewContentModeScaleAspectFit;
 [self.contentView addSubview:_imgPicture];

这是我的cellForRowAtIndexPath

RecipeTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"recipe_cell"];

if(cell == nil)
{
    cell = [[RecipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"recipe_cell"];
}
NSDictionary *dict = [recipeArray objectAtIndex:[indexPath row]];
cell.lblName.text = [dict valueForKey:@"name"];

if([@"data:image/jpg;base64,null" isEqualToString:[NSString stringWithFormat:@"%@,%@",[dict valueForKey:@"pictureType"], [dict valueForKey:@"picture"]]])
{
    cell.imgPicture.image = defaultImage;
}
else
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@,%@",[dict valueForKey:@"pictureType"], [dict valueForKey:@"picture"]]];
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    UIImage *ret = [UIImage imageWithData:imageData];
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    cell.imageView.image = [ImageExtension imageWithImage:ret convertToWidth:screenWidth];
}

return cell;

Screen shot of the resulting view

我已经尝试通过设置框架强制 UIImageView 位于原点 0, 0,但这没有帮助,我现在认为这可能是图像被调整大小的事实,然后 UITableViewCell 中的某些内容中断了,但不知道它可能是什么。对此提供一些帮助将不胜感激。

另请注意,我将所有这些作为 Storyboard ,并且得到了完全相同的结果,然后我想让我以编程方式尝试并获得相同的结果。

最佳答案

改变

cell.imageView.image
     ^^^^^^^^^

cell.imgPicture.image
     ^^^^^^^^^^

这将解决问题...

关于ios - UIImageView 在表格 View 中的图像左侧有奇怪的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448154/

相关文章:

ios - 隐藏 UISearchDisplayController 的 UISearchBar

ios - 登录到 facebook api 和预定的事件

objective-c - 如何让 NSOutline View 与绑定(bind)一起使用?

ios - 如何防止人们从 Parse 核心数据请求中获取应用程序 ID 和客户端 ID?

objective-c - 为什么结构和基本类型不需要指针?

objective-c - setObject :forKey setObject:forKeyedSubscript 和有什么区别

ios - 等待 block 完成以重新加载 UITableView 数据

iphone - cellForRowAtIndexPath 返回 nil

iphone - 这个警告是什么意思 : "setting the first responder view of the collection view but we don' t know its type (cell/header/footer)"

ios - 在 viewDidLoad 处将可调整大小的 UIImage 设置为 UIImageView 被忽略