我一直在使用一个UIImageView
子类,在这里找到,在 s 中设置异步下载的图像UITableViewCell
,保持正确的纵横比。该类如下:
internal final class ScaleAspectFitImageView: UIImageView {
/// Constraint to maintain same aspect ratio as the image.
private var aspectRatioConstraint: NSLayoutConstraint? = nil
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(frame:CGRect) {
super.init(frame: frame)
setup()
}
public override init(image: UIImage!) {
super.init(image: image)
setup()
}
public override init(image: UIImage!, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
setup()
}
override public var image: UIImage? {
didSet {
print("\nUpdating aspect ratio constraints")
updateAspectRatioConstraint()
print("Updated aspect ratio constraints\n")
}
}
private func setup() {
contentMode = .scaleAspectFit
updateAspectRatioConstraint()
}
/// Removes any pre-existing aspect ratio constraint, and adds a new one based on the current image
private func updateAspectRatioConstraint() {
// Remove any existing aspect ratio constraint
if let constraint = aspectRatioConstraint {
removeConstraint(constraint)
}
aspectRatioConstraint = nil
if let imageSize = image?.size, imageSize.height != 0 {
let aspectRatio = imageSize.width / imageSize.height
let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: aspectRatio, constant: 0)
addConstraint(constraint)
aspectRatioConstraint = constraint
}
}
}
我也AlamofireImage
用来下载里面的图片tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
,如下:
cell.embeddedImageImageView.layer.borderColor = UIColor.red.cgColor
cell.embeddedImageImageView.layer.borderWidth = 2
let placeholderImage = #imageLiteral(resourceName: "postImagePlaceholder")
if let embeddedImageURL = message.mediaURL {
let filter = AspectScaledToFitSizeFilter(size: cell.embeddedImageImageView.frame.size)
cell.embeddedImageImageView.af_setImage(withURL: embeddedImageURL, placeholderImage: placeholderImage, filter: filter)
} else {
cell.embeddedImageImageView.image = placeholderImage
}
但是,当图像下载时,它们被放置在单元格的内部embeddedImageImageView
,导致大小不正确。
以下是我的单元格的屏幕截图,其中我UIImageView
在ScaleAspectFitImageView
子类周围放置了一个红色边框。
我做错了什么导致我的图像尺寸不正确?