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

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

问题描述

我想用自定义TableViewCell实现一个显示图像的TableView。

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

为了简单起见,我简单地使用autolayout将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的高度Autolayout约束

  2. 修改UIImageView的框架

在此处查看方法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天全站免登陆