【发布时间】:2016-10-10 01:12:33
【问题描述】:
我有一个自定义的UITableViewCell,它有一个UIImageView。我从互联网上提取图像以填充单元格中的图像视图,因此每个图像的纵横比可以不同。当图像宽度大于其高度时,我想避免 UIImageView 中的顶部/底部填充。
我还想保持纵横比不变。我在storyboard 中布置了自定义表格视图单元格,约束将侧面固定到每个边距以及顶部和底部。我对 UIImageView 的高度也有限制。然后我尝试根据原始图像的纵横比更改高度限制。
import UIKit
import Kingfisher
import AVFoundation
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!
func populateCell(url: URL?) {
if let imageUrl = url {
if let url = URL(string: imageUrl) {
image.kf.setImage(with: url, placeholder: UIImage(named: "placeholder"), options: [], progressBlock: nil, completionHandler: { (theImage, error, cacheType, url) in
if let theImage = theImage {
let rect = AVMakeRect(aspectRatio: theImage.size, insideRect: CGRect(x: 0, y: 0, width: self.image.frame.width, height: 250))
self.imageHeightConstraint.constant = floor(rect.height)
}
})
}
}
}
}
这第一次效果很好。我得到了原始图像,根据 UIImageViews 的宽度/高度计算出它的纵横比。但是,如果我向下滚动并返回到我的第一个图像,事情就会变得不稳定。最初 UIImageViews 框架是 size : (343.0, 250.0),但是第二次 UIImageViews 框架是 1000/1000。
几件事:
我不知道为什么 UIImageViews 的宽度/高度是 1000/1000,看起来很奇怪。要么是细胞回收的东西,要么是设置高度限制,后来搞砸了尺寸。
我正在尝试的方法是否正常,这意味着它是有效的解决方案吗?如果没有,考虑到我正在使用具有自动布局和自动高度的
UITableView,是否有一种好方法可以根据图像的纵横比调整UIImageView的高度。
【问题讨论】:
-
找到解决方案了吗?
-
d= (-_- ) 一样,不要放弃!
标签: ios swift uitableview uiimageview kingfisher