如何在swift中使用NSLayoutConstraint根据屏幕大小更改设计

如何在swift中使用NSLayoutConstraint根据屏幕大小更改设计,swift,iphone,storyboard,size,nslayoutconstraint,Swift,Iphone,Storyboard,Size,Nslayoutconstraint,我已经为iPhone XR设计了一个使用故事板约束的屏幕,但这种设计在iPhone 7中变得很大,因此我想使用NSLayoutConstraints更改我的ContainerView的高度和宽度 我采取了: @IBOutlet weak var containerViewheight: NSLayoutConstraint! 这个ContainerView在iPhoneXR中的实际高度是300,所以我想在iPhone7中更改它 例如: if (iphone7) { self.contain

我已经为iPhone XR设计了一个使用故事板约束的屏幕,但这种设计在iPhone 7中变得很大,因此我想使用
NSLayoutConstraints
更改我的
ContainerView
的高度和宽度

我采取了:

@IBOutlet weak var containerViewheight: NSLayoutConstraint!
这个
ContainerView
在iPhoneXR中的实际高度是300,所以我想在iPhone7中更改它

例如:

if (iphone7) {
  self.containerViewheight.constant = 240
}

if (iphone SE) {
  self.containerViewheight.constant = 280
}

不幸的是,我对大小类知之甚少。

您可以随时询问
UIScreen
class方法
main
获取当前具体大小,它返回当前设备的具体大小

let deviceSize = UIScreen.main.bounds.size
但是您可能知道,
高度
宽度
根据设备的方向(横向或纵向)而变化

也许这个扩展可以帮助:

import UIKit

extension UIScreen {

    /// Retrieve the (small) width from portrait mode
    static var portraitWidth : CGFloat { return min(UIScreen.main.bounds.width, UIScreen.main.bounds.size.height) }

    /// Retrieve the (big) height from portrait mode
    static var portraitHeight : CGFloat { return max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)  }

    /// Retrieve the (big) width from landscape mode
    static var landscapeWidth : CGFloat { return max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) }

    /// Retrieve the (small) height from landscape mode
    static var landscapeHeight : CGFloat { return min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) }
}

您可以通过知道您希望容器高度与屏幕高度的比率来进行操作

例如:if
UIScreen.main.bounds.height
为您提供1000。你的合适容器高度是400。那么所需的容器高度与屏幕高度之比为400/1000或2/5

现在,你能做的就是写

containerViewheight.constant = (2/5)*UIScreen.main.bounds.height

对不起,我很困惑,你想问什么@swift@jacob在故事板中设计屏幕时,我已经给出了iphonexr中containerView的前导、尾随、顶部和高度限制。。。。但该视图在剩余的iphone尺寸中占据了更多的空间,因此我想根据iphone尺寸更改其高度。不要使用常量约束,如果希望根据屏幕尺寸更改,请使用相对约束。因此,让我们为您的前导和尾随设置插座参考,以调整宽度,然后检查是否按设备类型更新常量。我建议您根据视图宽度的百分比更改该常数。@jacob我可以获得正确的宽度bcs,我已经给出了前导和尾随,但根据设备类型确定了高度。。如何根据设备类型更改常量值。。。有代码吗??