2017-04-19 107 views
2

我一直在使用UIImageView子类,找到here,在UITableViewCell s内设置异步下载的图像,保持正确的宽高比。这个类如下:使用Alamofire设置正确尺寸图像时出现问题

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

我在做什么错误,是造成我的图片不大小合适?

回答

0

您是否首先将您的细胞图像视为ScaleAspectFitImageView的子类?

enter image description here

运行子你贴的原因EXC_BAD_ACCESS。所以我删除了aspectRatioConstraint属性和它们的用法并运行你的代码,一切工作都很完美。

ImageViews size themselves as expected