UITableView中的动态UIImageView大小

fab*_*ice 21 uitableview uiimageview ios autolayout swift

我想用一个显示图像的Custom TableViewCell实现一个TableView.

为了简单起见,我简单地使用autolayout将UIImageView放在tableviewcell中(如下图所示). 在此输入图像描述

我想要的是在UIImageView中显示图像,但是那些图像尺寸可以是任何东西并且是不一致的(肖像,风景,方形)......

因此,我希望显示具有固定宽度(设备宽度)的图像和相对于图像比例的动态高度.我想要这样的东西:
在此输入图像描述

遗憾的是,我无法达到这一结果.

以下是我实现它的方式 - (我使用Haneke从URL加载图像 - 存储在Amazon S3中的图像):

class TestCellVC: UITableViewCell {

    @IBOutlet weak var selfieImageView: UIImageView!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func loadItem(#selfie: Selfie) {        
        let selfieImageURL:NSURL = NSURL(string: selfie.show_selfie_pic())!

        self.selfieImageView.hnk_setImageFromURL(selfieImageURL, placeholder: nil, format: HNKFormat<UIImage>(name: "original"), failure: {error -> Void in println(error)
            }, success: { (image) -> Void in
                // Screen Width
                var screen_width = UIScreen.mainScreen().bounds.width

                // Ratio Width / Height
                var ratio =  image.size.height / image.size.width

                // Calculated Height for the picture
                let newHeight = screen_width * ratio

                // METHOD 1
                self.heightConstraint.constant = newHeight

                // METHOD 2
                //self.selfieImageView.bounds = CGRectMake(0,0,screen_width,newHeight)

                self.selfieImageView.image = image
            }
        )
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register the xib for the Custom TableViewCell
        var nib = UINib(nibName: "TestCell", bundle: nil)
        self.tableView.registerNib(nib, forCellReuseIdentifier: "TestCell")

        // Set the height of a cell dynamically
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 500.0

        // Remove separator line from UITableView
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None

        loadData()
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("TestCell") as TestCellVC


        cell.loadItem(selfie: self.selfies_array[indexPath.row])
        // Remove the inset for cell separator
        cell.layoutMargins = UIEdgeInsetsZero
        cell.separatorInset = UIEdgeInsetsZero

        // Update Cell Constraints
        cell.setNeedsUpdateConstraints()
        cell.updateConstraintsIfNeeded()
        cell.sizeToFit()

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

我对动态高度的计算是正确的(我打印过它).我已经尝试了两种方法(在代码中描述),但它们都没有工作:

  1. 设置UIImageView的Height Autolayout约束
  2. 修改UIImageView的框架

请参见方法1和2的结果: 图片 图2

sas*_*ash 16

在故事板中添加尾随,前导,下限和上限约束UIImageView.加载图像后,您需要做的就是为您的图像添加一个方面约束UIImageView.您的图像单元格看起来像这样:

class ImageTableViewCell: UITableViewCell {

    @IBOutlet weak var customImageView: UIImageView!

    internal var aspectConstraint : NSLayoutConstraint? {
        didSet {
            if oldValue != nil {
                customImageView.removeConstraint(oldValue!)
            }
            if aspectConstraint != nil {
                customImageView.addConstraint(aspectConstraint!)
            }
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        aspectConstraint = nil
    }

    func setCustomImage(image : UIImage) {

        let aspect = image.size.width / image.size.height

        let constraint = NSLayoutConstraint(item: customImageView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: customImageView, attribute: NSLayoutAttribute.height, multiplier: aspect, constant: 0.0)
        constraint.priority = 999

        aspectConstraint = constraint

        customImageView.image = image
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此查看DynamicTableWithImages的工作示例

  • 不幸的是,如果将图像提取为异步,则不会刷新单元格高度 - 我认为OP存在此问题. (4认同)
  • 如果您的图像是异步获取的,请查看 /sf/answers/2385531921/。 (2认同)

Jac*_*ack 11

在此输入图像描述

将图像加载到tableView中时,每个图像可以具有不同的宽高比.使用SDWebImage,我们可以从url获取图像 -

 testImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: { (downloadedImage, error, cache, url) in
            print(downloadedImage?.size.width)//prints width of image
            print(downloadedImage?.size.height)//prints height of image
        })
Run Code Online (Sandbox Code Playgroud)

UITableViewCell设置的ImageView为约束top,bottom,leading,trailing,fixed height constraint999优先级和改变height-constraint-constant根据图像.

 var cellFrame = cell.frame.size
 cellFrame.height =  cellFrame.height - 15
 cellFrame.width =  cellFrame.width - 15
 cell.feedImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: { (theImage, error, cache, url) in
            cell.feedImageHeightConstraint.constant = self.getAspectRatioAccordingToiPhones(cellImageFrame: cellFrame,downloadedImage: theImage!)

        })
Run Code Online (Sandbox Code Playgroud)

计算单元框架并根据它找到相应的高度.

  func getAspectRatioAccordingToiPhones(cellImageFrame:CGSize,downloadedImage: UIImage)->CGFloat {
        let widthOffset = downloadedImage.size.width - cellImageFrame.width
        let widthOffsetPercentage = (widthOffset*100)/downloadedImage.size.width
        let heightOffset = (widthOffsetPercentage * downloadedImage.size.height)/100
        let effectiveHeight = downloadedImage.size.height - heightOffset
        return(effectiveHeight)
    }
Run Code Online (Sandbox Code Playgroud)

Github上的示例


Roh*_*mar 0

从 imageView 中删除高度限制。选择以“方面”开头的图像视图的内容模式,例如:方面填充或方面适合(因为它适合您的要求)。

注意:您还需要设置行的高度,以便 imageView 适合它。使用

heightForRowAtIndexPath
Run Code Online (Sandbox Code Playgroud)

设置自定义行高。

  • 您好,我已经尝试过您的方法,但不起作用。原因是因为我用来加载图像的 Haneke 函数“self.selfieImageView.hnk_setImageFromURL”是异步的,所以在加载之前我并没有真正获得单元格的高度。 (3认同)