我正在尝试在imageView
内布置stackView
,但无法裁剪图像。如图所示,未插入任何图像时,布局正确完成:
但是,当我插入虚拟图像(人像图像)以测试contentMode
和clipsToBounds
时,它会拉伸,就像这样:
我已经阅读了post,还尝试在将imageView
放在UIView
内之前,先将其堆叠在stackView内,但仍然得到相同的结果。请注意,我希望我的两个标签采用其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)
])
有什么建议吗?