Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift How to resize an image inside a stackview

Tags:

xcode

ios

swift

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

Current Image

like image 612
SwiftER Avatar asked Jan 04 '23 09:01

SwiftER


1 Answers

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
like image 93
orxelm Avatar answered Jan 12 '23 15:01

orxelm