2017-03-05 160 views
2

我在堆棧視圖中有兩個項目,一個是圖像,另一個是標籤。我希望圖像根據其框架大小而不是堆棧大小調整大小,我如何改變這一點。Swift如何調整堆棧視圖中的圖像大小

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

回答

2

您可以添加高度和寬度的限制:

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