Swift如何在stackview中调整图像大小

时间:2017-03-05 18:29:57

标签: ios swift xcode

我在堆栈视图中有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

1 个答案:

答案 0 :(得分:3)

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

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])

只需确保按比例设置stackview的分布:

releaseInfoStack.distribution = .fillProportionally