使用AlamofireImage设置具有正确尺寸的图像故障

时间:2017-04-19 16:51:23

标签: uiimageview uiimage alamofireimage

我一直在使用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子类。

Screenshot of current image dimensions

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

1 个答案:

答案 0 :(得分:0)

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

enter image description here

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

ImageViews size themselves as expected