xcode Swift 如何在堆栈视图中调整图像大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42612270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:49:30  来源:igfitidea点击:

Swift How to resize an image inside a stackview

iosswiftxcode

提问by pprevalon

I have 2 items in a stack view one is an image and the other is a label. I want the image to resize according to its frame size not the size of stack how can i change this.

我在堆栈视图中有 2 个项目,一个是图像,另一个是标签。我希望图像根据其帧大小而不是堆栈大小调整大小,我该如何更改。

//stack code
lazy var releaseInfoStack:UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.spacing = 4
        v.alignment = .center
        v.axis = .horizontal
        return v
    }()

//my image
lazy var smallRealeaseImageIcon:UIImageView = {
        let v = UIImageView(frame:CGRect(x: 0, y: 0, width: 17, height: 17))
        v.contentMode = .scaleAspectFit
        v.image = UIImage(named: "link")
        return v
    }()

//this is the current image below but i want the link icon to be smaller

Current Image

当前图像

回答by orxelm

You can add constraints for height and width:

您可以为高度和宽度添加约束:

let imageViewWidthConstraint = NSLayoutConstraint(item: smallRealeaseImageIcon, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
let imageViewHeightConstraint = NSLayoutConstraint(item: smallRealeaseImageIcon, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
smallRealeaseImageIcon.addConstraints([imageViewWidthConstraint, imageViewHeightConstraint])

Just make sure to set the stackview's distribution to proportionally:

只需确保将堆栈视图的分布按比例设置:

releaseInfoStack.distribution = .fillProportionally