自动布局:获取 UIImageView 高度以正确计算单元格高度 [英] Auto-Layout: Get UIImageView height to calculate cell height correctly

查看:33
本文介绍了自动布局:获取 UIImageView 高度以正确计算单元格高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我只是在应该自动调整大小的单元格中使用文本标签.我通常对所有边(内容视图或邻居)施加约束,并将以下几行添加到我的 viewDidLoad():

So far I have been just using text labels within cells that should auto-size themselves. I usually put constraints to all of the edges (content view or neighbors) and add the following lines to my viewDidLoad():

// 190.0 is the actual height of my custom cell (see next image) in the storyboard containing a label and a randomly sized UIImageView
tableView.estimatedRowHeight = 190.0
tableView.rowHeight = UITableViewAutomaticDimension

现在,在尝试包含图像时,我遇到了几个问题.在一些研究中,我发现了几种用 Objective-C 编写的方法,但虽然我不确定哪些方法真正解决了我的核心问题,但我仍在努力处理复杂的 Objective-C 代码.所以继续:我的最终目标是获得一个包含正确大小(正确高度)单元格的表格,每个单元格包含一个标题和一个适合屏幕宽度的图像.这些图像可以具有不同的纵横比和不同的大小.为了简化一些挑战,我准备了一个新的、更简单的项目:

Now, when trying to include with images, I face several problems. During some research I found several approaches written in Objective-C but whereas I'm not sure which of those really addressed my central problem I'm still struggling with complex Objective-C code. So to resume: My final goal is to get a table with correctly sized (correct heights) cells, each containing a title and an image that fits the width of the screen. Those images can be of different aspect ratios and different sizes. To simplify some of the challenges, I prepared a new, more simple project:

  1. 首先,我创建了一个 UITableViewController 和一个 CustomCell 类,其中包含两个 IBOutlets title: StringpostedImage: UIImage>(UIImage 在故事板中随机调整大小)来配置单元格.我定义了对边缘和彼此的约束.
  1. First, I created a UITableViewController and a CustomCell class with two IBOutlets title: String and postedImage: UIImage (UIImage randomly sized in the storyboard) to configure the cells. I defined constraints to the edges and to each other.

  1. 构建时,两个单元格被配置为包含相同的图像,但它们是从两个具有不同大小和分辨率(900 x 171 与半尺寸 450 x 86)的单独文件中获取的.UIImage 视图模式设置为Aspect Fit",但由于到目前为止我无法让它以我想要的方式运行,我不确定这是正确的设置.虽然我曾期望根据重新缩放的 UIImage 计算单元格高度,包括我设置的约束,但它似乎基于图像文件的初始高度(如 171 和 86).它实际上并不适应实际的 UIImage 视图高度(我猜大约是 70).

在我的一个稍微复杂一点的项目中,我希望不同的图像能够自动适应屏幕的宽度,无论它们是纵向还是横向 - 如果它们的宽度小于屏幕的宽度,它们应该被放大.就像在上面的项目中一样,每个单元格的高度都应该适合故事板中的约束所定义的单个内容.无论如何,它从上面讨论的问题开始:我怎样才能让这两个单元格具有相同的、正确的高度,像故事板中定义的那样拥抱其内容?

In a somewhat more complex project of mine I want different images to automatically fit the width of the screen no matter whether they are portrait or landscape - and in case their width is less then the screen's width, they should be scaled up. Like in the project above each cell height should fit its individual content as defined by the constraints in the storyboard. Anyway, it starts with the problem discussed above: How can I let those two cells have the same, correct height, hugging its content like defined in the storyboard?

感谢一百万的帮助!

推荐答案

所以我认为根本问题是一种鸡和蛋的问题.

So I think the underlying issue is a kind of chicken and egg problem.

为了使图像纵横匹配"UIImageView,系统需要视图的大小,但我们希望在之后确定视图的高度 在给定视图宽度的情况下拟合图像的方面.

In order to 'aspect fit' the image to the UIImageView the system needs a size for the view, and yet we would like the height of the view to be determined after aspect fitting the image given a known width for the view.

一种解决方法是自己计算图像的纵横比,并在我们设置图像时将其设置为 UIImageView 上的约束.这样,自动布局系统就有足够的信息来调整视图的大小(宽度和纵横比).

A workaround is to calculate the aspect ratio of the image ourselves and set it as a constraint on the UIImageView when we set the image. That way the auto layout system has enough information to size the view (a width and an aspect ratio).

所以我将您的自定义单元格类更改为:

So I changed your custom cell class to:

class CustomCell: UITableViewCell {

    @IBOutlet weak var imageTitle: UILabel!

    @IBOutlet weak var postedImageView: UIImageView!

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

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

    func setPostedImage(image : UIImage) {

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

        aspectConstraint = NSLayoutConstraint(item: postedImageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: postedImageView, attribute: NSLayoutAttribute.Height, multiplier: aspect, constant: 0.0)

        postedImageView.image = image
    }

}

然后在委托中执行此操作而不是直接设置图像:

And then in the delegate do this instead of setting the image directly:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell

        cell.imageTitle.text = titles[indexPath.row]

        let image = images[titles[indexPath.row]]!
        cell.setPostedImage(image)

        return cell
}

你会得到:

希望这有帮助!

这篇关于自动布局:获取 UIImageView 高度以正确计算单元格高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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