iOS:UIImageView随着UITableView.rowHeight的变化而改变,如何避免?
这的确是一个问题,我学习iOS
而试图建立一个应用程序iOS:UIImageView随着UITableView.rowHeight的变化而改变,如何避免?
我需要显示的图像,标签上UITableViewCell
。下面的代码对我来说是这样的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.imageView.image = [self getImageNameForRow:indexPath.row];
cell.textLabel.text = self.features[(NSUInteger) indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
return cell;
}
问题是图像尺寸变大了,我期望。所以我试图增加行的高度
self.tableView.rowHeight = 80;
但是,然后图像也放大。
如何我把我的图像尺寸固定,同时增加(或改变)行的大小?
的问题是,您使用的是默认的表视图单元格样式。这种风格带有一个内置的textLabel
和一个imageView
,后者是一个带有约束的UIImageView,因此它的大小被调整为填充单元格的高度。但你也说
cell.imageView.contentMode = UIViewContentModeScaleAspectFit
这意味着作为图像视图的增长,图像的增长与它 - 你看到什么。
正如我解释here所述,解决方案是将图像缩小到您想要的实际大小 - 并将图像视图的contentMode设置为center
。类似这样的:
UIImage* im = [self getImageNameForRow:indexPath.row];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(36,36), YES, 0);
[im drawInRect:CGRectMake(0,0,36,36)];
UIImage* im2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = im2;
cell.imageView.contentMode = UIViewContentModeCenter;
将36,36
更改为您实际需要的大小。
无论如何,这是一个很好的做法。保持图像的尺寸比实际显示所需要的尺寸要大(浪费的内存量呈指数增长,因为面积在一维的平方的数量级上),这是可怕的内存浪费。所以你应该总是大小的图像下降到他们的实际显示大小。Stack Overflow上有很多很多的代码,显示了许多其他的方法来做到这一点。
我相信你这里的主要问题是图像太大。如果图像仅为40x40,则它会显示为tableViewCell高度的一半(当它是80时)。 IIRC UITableViewCell中的UIImageView伸展到单元格的高度,如果足够大,图像将始终填充它。
三件事情你可以做:
1)缩小影像到你想要的尺寸大小。
2)手动更改的ImageView的框架,像这样:
cell.imageView.image = [self getImageNameForRow:indexPath.row];
CGPoint center = cell.imageView.center;
CGRect frame = cell.imageView.frame;
frame.size.width = 40;
frame.size.height = 40;
cell.imageView.frame = frame;
cell.imageView.center = center;
我不是,如果你需要缓存的中心和完全肯定重新设置它的框架改变后或不(中的UITableViewCell可能会自动执行此操作)。
3)制作一个具有固定大小UIImageView的自定义UITableViewCell子类。我详细说明了如何在我的博客here上做到这一点。
我推荐1或3
太棒了,正是我在找的东西,谢谢你与我分享! – daydreamer 2014-08-31 01:04:51