2

我一直在使用一个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,导致大小不正确。

以下是我的单元格的屏幕截图,其中我UIImageViewScaleAspectFitImageView子类周围放置了一个红色边框。

当前图像尺寸的屏幕截图

我做错了什么导致我的图像尺寸不正确?

4

1 回答 1

0

您是否首先将单元格的图像视图设为 ScaleAspectFitImageView的子类?

在此处输入图像描述

运行您发布的子类会导致 EXC_BAD_ACCESS。因此,我删除了aspectRatioConstraint属性及其用法并运行了您的代码,一切正常。

ImageViews 按预期调整大小

于 2017-04-28T21:05:04.477 回答