iPhone:将UIImage放入TableView节头,拉伸问题

5

大家好,我将一个UIImage放在了我的UITableVIew的section header中。为此,我使用了一些我在互联网上找到的代码:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

self.imageViewForImage.image = [helperClass resizeImage:[self.offerItem objectForKey: @"picture"] forSize:CGSizeMake(280.0, 280.0) ];

[self.imageViewForImage.layer setBorderColor: [[UIColor blackColor] CGColor]];
[self.imageViewForImage.layer setBorderWidth: 1.2];

self.imageViewForImage.contentMode = UIViewContentModeBottom;
return self.imageViewForImage;}


-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return 320;
    return 1.0;
}

起初,图像完全按照 iPhone 的 320px 宽度进行缩放。但后来我发现,我的整个 UITableView 的 contentMode 属性设置为 "UIViewContentModeScaleToFill"。所以我添加了一行代码,告诉我的 UIImageView 不要进行缩放。在我的情况下,我将其设置为 "UIViewContentModeBottom"。
问题:这整个过程都有效,图像最终以 280x280 的纵横比显示,但我围绕图片做的边框仍然被拉伸/调整到 iPhone 的整个宽度...?!
我无法解决这个问题,因为我想要在 UIImage 周围加上边框。
感谢任何对此的帮助。
编辑:有人有什么想法吗,这里出了什么问题?
1个回答

9
您的UIImageView有一个层,其内容设置为您的图像。层的大小等于imageView的大小,但图像的大小小于它。因此,当将contentMode设置为视图时,它会告诉它的层在内容大小小于层大小时在底部绘制层的内容。因此,即使您调整了其内容图像的大小,层的大小(以及其框架的大小)仍然相同。
问题在于您试图调整图像的大小,而应该调整UIImageView的大小。代码的这一部分应该类似于以下内容:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] init];

    self.imageViewForImage.frame = CGRectMake(20, 20, 280, 280);
    self.imageViewForImage.image = [self.offerItem objectForKey:@"picture"];
    self.imageViewForImage.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

    [self.imageViewForImage.layer setBorderColor: [[UIColor blackColor] CGColor]];
    [self.imageViewForImage.layer setBorderWidth: 1.2];

    [headerView addSubview:self.imageViewForImage];
    return [headerView autorelease];
}

希望这能帮到你!

更新:问题在于此方法返回的视图被tableView重新构建,以填充整个表头。因此,我们必须创建一个实际上是表头视图的视图,并在其上放置一个imageView。


谢谢你的回答!不幸的是,它并没有起作用。问题在于:如果我插入你的代码,整个图像会被拉伸到iPhone的宽度... - dac
是的,太棒了!非常感谢你。我试了好几个小时才把边框弄对,而你做到了!祝你有美好的一天,再次感谢。 - dac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接