首页 > 解决方案 > Swift:无法在 stackView 中剪辑图像

问题描述

我正在尝试在imageView内部布局stackView,但无法剪辑图像。未插入图像时布局已正确完成,如下所示:

在此处输入图像描述

但是,当我插入一个虚拟图像(肖像图像)来测试contentModeandclipsToBounds时,它会被拉伸,如下所示:

在此处输入图像描述

我已经阅读了这篇文章,并且还尝试在堆叠到 stackView 之前布局imageView内部 a ,但它仍然给出了相同的结果。UIView请注意,我希望我的两个标签采用它intrinsicContentSize,因为它titleLabel可能占用 1 或 2 行。我希望 imageView 相应地调整。

我的实现:

   let drawingPreviewImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.image = UIImage(named: "testImage")
        iv.backgroundColor = .lightGray
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.layer.masksToBounds = true
        return iv
    }()

    let stackView = UIStackView(arrangedSubviews: [
            drawingPreviewImageView,
            numberLabel,
            titleLabel,
            ])
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical
        stackView.spacing = 4
        stackView.isLayoutMarginsRelativeArrangement = true
        stackView.layoutMargins = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4 )

        addSubview(stackView)

        NSLayoutConstraint.activate([
            stackView.topAnchor.constraint(equalTo: topAnchor),
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
            stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
            ])

有什么建议吗?

标签: swift

解决方案


推荐阅读