我有一个 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;
我已经尝试通过设置框架强制 UIImageView
位于原点 0, 0,但这没有帮助,我现在认为这可能是图像被调整大小的事实,然后 UITableViewCell
中的某些内容中断了,但不知道它可能是什么。对此提供一些帮助将不胜感激。
另请注意,我将所有这些作为 Storyboard ,并且得到了完全相同的结果,然后我想让我以编程方式尝试并获得相同的结果。
最佳答案
改变
cell.imageView.image
^^^^^^^^^
到
cell.imgPicture.image
^^^^^^^^^^
这将解决问题...
关于ios - UIImageView 在表格 View 中的图像左侧有奇怪的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448154/