Set UIImageView AspectRatio constraint programmatically in swift 3

霸气de小男生 提交于 2019-12-10 14:45:49

问题


I have an UIImageView in storyboard which AspectRatio is 1:1, that I want to change to 2:1 programmatically in ViewController in some cases. I create reference of that constraint in ViewController but unable to set the constraint.


回答1:


You can change constraint programmatically in swift 3

let aspectRatioConstraint = NSLayoutConstraint(item: self.YourImageObj,attribute: .height,relatedBy: .equal,toItem: self.YourImageObj,attribute: .width,multiplier: (2.0 / 1.0),constant: 0)
self.YourImageObj.addConstraint(aspectRatioConstraint)



回答2:


As it's stated in Apple's guide, there're three ways to set constraints programmatically:

  • You can use layout anchors
  • You can use the NSLayoutConstraint class
  • You can use the Visual Format Language

The most convenient and fluent way to set constraints is using Layout Anchors.

It's just one line of code to change aspect ratio for your ImageView

imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true

To avoid "[LayoutConstraints] Unable to simultaneously satisfy constraints." you should add reference to your ImageView's height constraint then deactivate it:

heightConstraint.isActive = false



回答3:


Set the multiplier of the constraint to 0.5 or 2 depending on your constraint condition, It'll become 2:1



来源:https://stackoverflow.com/questions/44668106/set-uiimageview-aspectratio-constraint-programmatically-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!