2016-12-16 82 views

回答

0

我不久前有這個完全相同的問題。

首先,您應該將圖像內容模式設置爲Aspect Fit,但這並不足以支持但是

您每次需要加載新圖像時都必須更改imageView的寬高比約束。基本上,你需要做的是:

  1. 獲取圖像的寬度和高度
  2. 計算寬高比let aspectRatio = Float(image.height)/Float(image.width)
  3. 使用的是長寬比爲您創造圖像視圖的新高寬比的約束。

這是我的代碼的複製粘貼(與添加評論)我管理這個問題。希望它能幫助你。

// aspectRatioCnst is IBOutlet reference to aspect ratio constraint I've set on mainImageView in Storyboard 
    if let aspectRatioCnst = aspectRatioCnst { 
     aspectRatioCnst.isActive = false 
    } 
    let aspectRatio = Float(imagePost.height)/Float(imagePost.width) 
    aspectRatioCnst = NSLayoutConstraint(
     item: self.mainImageView, 
     attribute: NSLayoutAttribute.height, 
     relatedBy: NSLayoutRelation.equal, 
     toItem: self.mainImageView, 
     attribute: NSLayoutAttribute.width, 
     multiplier: CGFloat(aspectRatio), 
     constant: 0) 
    if let aspectRatioCnst = aspectRatioCnst { 
     self.mainImageView.addConstraint(aspectRatioCnst) 
     aspectRatioCnst.isActive = true 
     self.mainImageView.layoutIfNeeded() 
    } 
    if let image = imagePost.loadedImage { 
     self.mainImageView.image = image 

    } else if let imageURL = URL(string: imagePost.fileURL) { 
     DispatchQueue.global(qos: .background).async { 
      // UIImage extension with downloadedFromURL method 
      UIImage.downloadedFromURL(url: imageURL, withCallback: { (image) -> (Void) in 
       DispatchQueue.main.async { 
        self.imageLoadingActivityIndicator.stopAnimating() 
        self.mainImageView.image = image 
        self.imagePost?.loadedImage = image 
       } 
      }) 
     } 
    } 
+0

如果什麼形象是異步下載。那麼代碼將如何知道圖像的高度和寬度? –

+0

這是一個很好的觀點。我以爲我不必複製那部分,但自從你問了以後,我更新了我的答案。附:在指向圖片URL的響應JSON中,我得到了圖片的高度和寬度,所以我不必計算它。 – JPetric

+0

基本上,我首先下載所有圖像元數據,其中我有每個圖像的高度和寬度以及我可以下載圖像的URL。然後當我出列表格視圖單元格時,我只是異步下載圖像。希望我澄清一點。 – JPetric

0

首先設置您的底部內容這樣的高度,

enter image description here

然後設置你的形象約束這樣的,

enter image description here

那麼做到這一點在你的代碼,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

     let imageNew = UIImage(named: "test") //Set your image here 
     let oldWidth = imageNew!.size.width 
     let scaleFactor = tableView.frame.size.width/oldWidth 

     let newHeight = imageNew!.size.height * scaleFactor 
     let newWidth = oldWidth * scaleFactor 

     //Finally to get cell size just add the bottom part height for othercontents to ImageHeight here 
     let CellSize = CGSize(width: newWidth, height: (newHeight + 40)) 
     return CellSize.height 

    } 


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell 
     cell.NewImage.image = UIImage(named: "test") 
     return cell 

    } 

你應該得到的財產以後這樣的, enter image description here