简体   繁体   中英

Swift How to resize an image inside a stackview

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.

//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

目前的形象

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM