UITableView 中的动态 UIImageView 大小 [英] Dynamic UIImageView Size Within UITableView

查看:25
本文介绍了UITableView 中的动态 UIImageView 大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个带有显示图像的自定义 TableViewCell 的 TableView.

I want to implement a TableView with a Custom TableViewCell showing an image.

为了简单起见,我只是使用自动布局(如下所示)将 UIImageView 放在 tableviewcell 中.

To make this simple, I simply put a UIImageView inside a tableviewcell using autolayout (illustrated below).

我想要的是在 UIImageView 中显示图像,但是这些图像尺寸可以是任何尺寸并且不一致(纵向、横向、方形)...

What I want is to display the image inside a UIImageView however those images dimensions can be anything and are inconsistent (portrait, landscape, square) ...

因此,我希望显示具有固定宽度(设备的宽度)和动态高度的图像,以尊重图像的比例.我想要这样的东西:

Therefore, I'm looking to display an image with a fixed width (the width of the device) and a dynamic height that respect the ratio of the images. I want something like this:

不幸的是我没能达到那个结果.

I unfortunately didn't manage to reach that result.

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

Here's how I implemented it - (I'm using Haneke to load the image from an URL - image stored in 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
    }
}

我对动态高度的计算是正确的(我已经打印出来了).我已经尝试了这两种方法(在代码中描述),但都没有奏效:

My calculation of the dynamic Height is correct (I've printed it). I've tried both method (describe in the code) but none of them worked:

  1. 设置 UIImageView 的高度自动布局约束
  2. 修改UIImageView的frame

在此处查看方法 1 和 2 的结果:

See Results of Method 1 and 2 here:

推荐答案

在情节提要中为 UIImageView 添加尾随、前导、底部和顶部约束.加载图像后,您需要做的就是向 UIImageView 添加一个方面约束.您的图像单元格看起来像这样:

In the storyboard add trailing, leading, bottom and top constraints to your UIImageView. After you load your image all you need to do is add an aspect constraint to your UIImageView. Your images cell would look something like this:

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
    }
}

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

You can check working example here DynamicTableWithImages

这篇关于UITableView 中的动态 UIImageView 大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆