我一直在使用UIImageView
子类,找到here,在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
子类。
我做错了什么导致我的图片尺寸不正确?