是否可以使用 AutoLayout 在运行时根据屏幕高度或屏幕宽度中的最大者制作 1:1 的纵横比?

Is it possible to use AutoLayout to make an aspect ratio of 1:1 based on the largest of either Screen Height or Screen width, at runtime?

我对特征和约束感到非常困惑。

我有一个视图需要 1:1 比例,并且它的大小需要在运行时和所有设备方向上取决于屏幕宽度或屏幕高度中的较大者.

最重要的是,我需要将它从屏幕中心向下移动,移动量是在运行时根据方向和 iPhone 与 iPad.[=13 计算得出的=]

在代码中完成所有这些并从此视图中删除所有 AutoLayout 约束是否可行或更好?

我读过这个:

还有这个:https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/Size-ClassSpecificLayout.html

但我似乎仍然无法让它做我想做的事。

谁能解释一下我需要做什么?

谢谢

您至少需要将这 2 个约束添加到情节提要中的 UIView。 第一个将用于纵横比,第二个将用于 UIView 的宽度,其值为常量。 您将在名为 widthConstraint 的 UIViewController class 中添加第二个约束的出口 在委托函数 ViewWillAppear() 上,您将添加计算最大边的代码,并将该值添加到约束常量。

UIView.animate(withDuration: 0.0) {
        let largestOfScreenSide = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height)
        self.widthConstraint.constant = largestOfScreenSide
        self.view.layoutIfNeeded()
    }