2017-04-19 133 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