[英]Set UIImageView AspectRatio constraint programmatically in swift 3
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. 我在故事板中有一个UIImageView,AspectRatio是1:1,在某些情况下,我想在ViewController中以编程方式更改为2:1。 I create reference of that constraint in ViewController but unable to set the constraint.
我在ViewController中创建了该约束的引用,但无法设置约束。
You can change constraint programmatically in swift 3 您可以在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)
As it's stated in Apple's guide , there're three ways to set constraints programmatically: 正如Apple指南中所述 ,有三种方法可以通过编程方式设置约束:
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的宽高比
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true
To avoid "[LayoutConstraints] Unable to simultaneously satisfy constraints." 避免“[LayoutConstraints]无法同时满足约束条件。” you should add reference to your ImageView's height constraint then deactivate it:
你应该添加对ImageView的高度约束的引用然后停用它:
heightConstraint.isActive = false
根据约束条件将约束的乘数设置为0.5或2,它将变为2:1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.