且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 iOS 中以编程方式设置纵横比约束?

更新时间:2023-02-04 10:35:17

像这样.尝试一次.

[self.yourview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.yourview addConstraint:[NSLayoutConstraint
                                  constraintWithItem:self.yourview
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:self.yourview
                                  attribute:NSLayoutAttributeWidth
                                  multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
                                  constant:0]];

或代替 (self.yourview.frame.size.height/self.yourview.frame.size.width) 您可以使用任何浮点值.谢谢.

or in the place of (self.yourview.frame.size.height / self.yourview.frame.size.width) you can use any float value. Thanks.

Swift 3.0 -

self.yourview!.translatesAutoresizingMaskIntoConstraints = false
self.yourview!.addConstraint(NSLayoutConstraint(item: self.yourview!,
                                          attribute: NSLayoutAttribute.height,
                                          relatedBy: NSLayoutRelation.equal,
                                          toItem: self.yourview!,
                                          attribute: NSLayoutAttribute.width,
                                          multiplier: self.yourview.frame.size.height / self.yourview.frame.size.width,
                                          constant: 0))