簡體   English   中英

表格視圖單元格中的情節提要板圖像視圖

[英]Storyboard imageview in a tableview cell

我在tableview的tableview單元格內有一個imageview。 我想要實現的是它應該根據它包含的圖像動態調整imageview的大小。

在此處輸入圖片說明

我不久前也遇到了同樣的問題。

首先,您應該將圖像內容模式設置為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
                }
            })
        }
    }

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

在此處輸入圖片說明

然后像這樣設置圖像約束

在此處輸入圖片說明

然后在您的代碼中執行此操作

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

    }

你應該得到這樣的東西 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM