2016-12-16 81 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