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

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

问题描述

到目前为止,我一直只使用细胞内的文本标签应自动调整大小本身。我通常把约束,所有的边缘(内容视图或邻居),并添加以下行到我的 viewDidLoad中()

  // 190.0是我的自定义单元格包含一个标签的实际高度(见下图)在故事板和一个随机大小的UIImageView
tableView.estimatedRowHeight = 190.0
tableView.rowHeight = UITableViewAutomaticDimension

现在,试图用图像,包括什么时候,我面临着几个问题。在一些研究,我发现用Objective-C的几种方法,但是,而我不知道它的真正解决我的核心问题我还是复杂的Objective-C code挣扎。因此,要恢复:我的最终目标是获取与大小正确(正确的高度)的表格单元格,每个都包含一个标题和适应屏幕宽度的图像。这些图像可以是不同的长宽比和不同的尺寸。为了简化一些挑战,我prepared一个新的,更简单的项目:


  1. 首先,我创建了一个的UITableViewController CustomCell 类有两个IBOutlets 标题:字符串 postedImage:UIImage的(UIImage的情节板中随机​​大小)配置细胞。我定义的约束的边缘和彼此。

<醇开始=2>
  • 当建,两个单元得到配置含有相同的图像,但它们是从具有不同的尺寸和分辨率两个单独的文件中取出(900×171对半尺寸450×86)。该UIImage的视图模式设置为宽适应但我不能让它运行的方式我想到目前为止,我不知道这是正确的设置。而我曾预计到基于所述重新缩放的UIImage(含)我已设定的约束来计算的单元格的高度,它似乎是基于该图像文件(以便171和86)的初始高度。它实际上并不适应实际的UIImage视图高度(约70我猜)。

  • 在我的一个较为复杂的项目,我想不同的图像自动适应屏幕的宽度,无论他们是否是纵向还是横向 - 在情况下,它们的宽度小于屏幕的宽度,就应该扩大规模。就像在每个单元的高度上面的项目在故事板约束的定义应该适合其个人的内容。无论如何,它开始与上文所讨论的问题:我怎样才能让这两个单元具有相同的,正确的高度,拥抱它的内容,如情节板中定义的

    万分感谢您的帮助!


    解决方案

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

    在以方面配合的形象在的UIImageView 系统需要一个尺寸的观点,但我们想视图的高度确定装修方面给出的看法已知宽度的形象。

    一个解决方法是计算图像自身的纵横比,并将其设置为一个约束的UIImageView 当我们设置图像。这种方式自动布局系统有足够的信息,以大小的视图(宽度,高宽比)。

    于是我改变了你的自定义单元格类:

     类CustomCell:{的UITableViewCell    @IBOutlet弱VAR imageTitle:的UILabel!    @IBOutlet弱VAR postedImageView:UIImageView的!    内部VAR aspectConstraint:NSLayoutConstraint? {
            didSet {
                如果属性oldValue!= {为零
                    postedImageView.removeConstraint(属性oldValue!)
                }
                如果aspectConstraint!= {为零
                    postedImageView.addConstraint(aspectConstraint!)
                }
            }
        }    覆盖FUNC prepareForReuse(){
            超。prepareForReuse()
            aspectConstraint =零
        }    FUNC setPostedImage(图片:UIImage的){        让纵横= image.size.width / image.size.height        aspectConstraint = NSLayoutConstraint(项目:postedImageView,属性:NSLayoutAttribute.Width,relatedBy:NSLayoutRelation.Equal,toItem:postedImageView,属性:NSLayoutAttribute.Height,事半功倍:一方面,恒:0.0)        postedImageView.image =图像
        }}

    然后在委托做的,而不是图像直接设置这样的:

     覆盖FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath) -  GT; {的UITableViewCell
            让细胞= tableView.dequeueReusableCellWithIdentifier(细胞,forIndexPath:indexPath)作为CustomCell        cell.imageTitle.text =标题[indexPath.row]        让图像=图像[标题[indexPath.row]!
            cell.setPostedImage(图)        回报细胞
    }

    和您将获得:

    希望这有助于!

    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
    

    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. 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. When built, two cells get configured containing the same image but they are fetched from two individual files with different sizes and resolutions (900 x 171 vs. half-sized 450 x 86). The UIImage view mode is set to "Aspect Fit" but as I couldn't get it run the way I want so far I'm not sure this is the right setting. Whereas I had expected the cell height to be calculated based on the rescaled UIImage inclusively the constraints I had set, it seems to be based on the initial height of the image files (so 171 and 86). It doesn't actually adapt to the actual UIImage view height (around 70 I'd guess).

    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?

    Thanks a million for any help!

    解决方案

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

    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.

    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
    }
    

    And you will get:

    Hope this helps!

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

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