swift - Swift:无法在 stackView 中剪辑图像
问题描述
我正在尝试在imageView
内部布局stackView
,但无法剪辑图像。未插入图像时布局已正确完成,如下所示:
但是,当我插入一个虚拟图像(肖像图像)来测试contentMode
andclipsToBounds
时,它会被拉伸,如下所示:
我已经阅读了这篇文章,并且还尝试在堆叠到 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)
])
有什么建议吗?