UIImageView not correctly resizing in self sizing cells iOS 8
我正在尝试实现与9gag应用类似的功能,其中单元会根据图像的大小自动调整大小。宽度紧贴侧面,但高度根据需要调整大小。
我有一个包含标题的标签,以及它上面的UIImageView和下面的图像(我具有共享图标等)。我将图像的约束设置为UIImageView,将较低的共享图标设置为前导和尾随空格。看起来我尝试过进行宽屏调整时会切换视图的"模式"(即宽屏填充,宽高比适合)的每种组合,它可以正确调整图像的大小,但会在底部的上下两边增加一堆填充图片(下面包括屏幕截图)
标签和图标都有适当的约束集(据我所知)
我已经搜索了数小时,试图找到遇到类似问题的人,但无济于事,我似乎找不到任何有关使用大小可能有所变化的图像的自定尺寸单元的信息。
谁能指出我的正确方向或知道我的问题的解决方案?一如既往地感谢所有帮助!
这是由于
虽然图像视图的宽度受前,后空间限制调整大小,但没有任何限制其高度的功能,因此它保持与原始图像高度相同。
解决方案是计算图像的宽高比并将其设置为对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | @interface PostImageViewCell() @property (nonatomic, strong) NSLayoutConstraint *aspectConstraint; @end @implementation PostImageViewCell - (void) setAspectConstraint:(NSLayoutConstraint *)aspectConstraint { if (_aspectConstraint != nil) { [self.postImage removeConstraint:_aspectConstraint]; _aspectConstraint = nil; } if (aspectContraint != nil) { [self.postImage addConstraint:aspectConstraint]; _aspectConstraint = aspectConstraint } } - (void)setPicture:(UIImage *)image { CGFloat aspect = image.size.width / image.size.height; self.aspectConstraint = [NSLayoutConstraint constraintWithItem:self.postImage attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.postImage attribute:NSLayoutAttributeHeight multiplier:aspect constant:0.0]; [self.postImage setImage:image]; } @end |
据我所知,您实际上无法从Interface Builder调整图像大小。您将必须在ViewController.m文件中手动编写代码。有这样的事情:
1 2 3 4 5 6 7 8 9 | - (void) adjustImageSize{ CGSize imageSize = self.imageView.image.size; CGSize imageViewSize = self.imageView.frame.size; float imageAspectRatio = imageSize.width/imageSize.height; CGRect frame = self.statusImage.frame; frame.size.height =imageViewSize.width/imageAspectRatio; self.imageView.frame = frame; // set your Cell's frame here, based on your other constraints (labels/buttons etc), after you have resized your image } |
您可以从tableView数据源函数调用此函数。然后添加此委托函数以告知tableView每个单元格的动态高度。
1 2 3 4 | - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; return cell.frame.size.height; } |
这就是我为基于NewsFeed的应用程序动态调整图像大小的方式。希望这可以帮助。
我也有同样的问题。
我注意到该单元格将根据您的imageView中的图像计算其大小,并且它忽略了UIImageView会更改图像的大小以使其适合其边界。
示例:您的图像尺寸为1000x1000。如果将内容模式设置为"宽高比",则UIImageView将以其宽度显示图像。因此显示的图像可能具有iPhone的宽度-例如750像素,高度750像素(正方形)。
现在,单元将调整自身大小,就好像imageView将以其原始格式显示图像一样。 1000x1000。这导致不必要的空白。
我现在的解决方法是手动缩小图像大小,但这非常昂贵,并且还会给我的UI带来其他问题。
您找到更好的解决方案了吗?