在 swift 3 中以编程方式设置 UIImageView AspectRatio 约束
Set UIImageView AspectRatio constraint programmatically in swift 3
我在情节提要中有一个 UIImageView,其 AspectRatio 是 1:1,在某些情况下我想在 ViewController 中以编程方式更改为 2:1。我在 ViewController 中创建了该约束的引用,但无法设置该约束。
根据你的约束条件设置约束的乘数为0.5或者2,就会变成2:1
您可以在 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)
如 Apple's guide 中所述,可以通过三种方式以编程方式设置约束:
- 您可以使用布局锚点
- 你可以使用 NSLayoutConstraint class
- 您可以使用视觉格式语言
设置约束最方便流畅的方法是使用布局锚点。
只需 一行 代码即可更改 ImageView 的纵横比
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true
为了避免[LayoutConstraints] 无法同时满足约束。您应该添加对 ImageView 高度约束的引用然后停用它:
heightConstraint.isActive = false
我在情节提要中有一个 UIImageView,其 AspectRatio 是 1:1,在某些情况下我想在 ViewController 中以编程方式更改为 2:1。我在 ViewController 中创建了该约束的引用,但无法设置该约束。
根据你的约束条件设置约束的乘数为0.5或者2,就会变成2:1
您可以在 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)
如 Apple's guide 中所述,可以通过三种方式以编程方式设置约束:
- 您可以使用布局锚点
- 你可以使用 NSLayoutConstraint class
- 您可以使用视觉格式语言
设置约束最方便流畅的方法是使用布局锚点。
只需 一行 代码即可更改 ImageView 的纵横比
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true
为了避免[LayoutConstraints] 无法同时满足约束。您应该添加对 ImageView 高度约束的引用然后停用它:
heightConstraint.isActive = false