防止垂直UIStackView拉伸子视图? [英] Prevent vertical UIStackView from stretching a subview?

查看:333
本文介绍了防止垂直UIStackView拉伸子视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有垂直UIStackView的UITableViewCell,当前具有.alignment =填充和distribution =填充.在堆栈视图中,我有一个UILabel和一个UIImageView.

I have a UITableViewCell with a vertical UIStackView that currently has .alignment = fill and distribution = fill. Inside the stack view, I have a UILabel and a UIImageView.

标签应保持对齐并在stackview的宽度上延伸(确实如此).图像视图具有宽高比适合的内容模式,应位于堆栈视图的中间.我以为这是我想要的工作,直到我在UIImageView上设置了背景颜色,然后才意识到,尽管图像本身看起来正确(缩放并居中),但视图本身却在整个stackview的整个宽度上延伸(就像标签一样)确实如此.)

The label should be left aligned and stretch across the width of the stackview (and it does). The image view has a content mode of aspect fit and should be centered in the middle of the stackview. I thought this was working as I wanted it to until I set a background color on the UIImageView and then realized that while the image itself appears correct (scaled and centered) the view itself stretches across the full width of the stackview (just like the label does).

是否可以使标签延伸堆栈视图的宽度,而不延伸图像视图的宽度?理想情况下,我希望图像视图只是缩放图像的大小,并且一直延伸到堆栈视图的边缘.

Is it possible to have the label stretch the width of the stack view but not the image view? Ideally, I'd like the image view to just be the size of the scaled image and not stretch all the way to the edges of the stack view.

推荐答案

进行以下更改:

  1. 将堆栈视图的对齐方式设置为.center而不是.fill.
  2. 将标签的宽度限制为等于堆栈视图的宽度.
  3. 在代码中,当您设置图像视图的图像时,还要在图像视图上创建长宽比约束,如下所示:

  1. Set your stack view's alignment to .center instead of .fill.
  2. Constrain the label's width to equal the stack view's width.
  3. In code, when you set the image view's image, also create an aspect-ratio constraint on the image view, like this:

class MyCell: UITableViewCell {
    @IBOutlet private var myImageView: UIImageView!
    private var imageViewAspectConstraint: NSLayoutConstraint?

    func setImage(_ image: UIImage) {
        myImageView.image = image

        imageViewAspectConstraint?.isActive = false
        imageViewAspectConstraint = myImageView.widthAnchor.constraint(
            equalTo: myImageView.heightAnchor,
            multiplier: image.size.width / image.size.height)
        imageViewAspectConstraint!.isActive = true
    }
}

请注意,由于可以重复使用单元格,因此如果存在单元格比例约束,则还必须删除它.我发布的代码使用imageViewAspectConstraint保存约束,并在图像更改时将其删除.

Note that, since cells can be reused, you also have to remove a prior aspect-ratio constraint if there is one. The code I posted uses imageViewAspectConstraint to save the constraint and remove it when the image changes.

这篇关于防止垂直UIStackView拉伸子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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