swift - 如何在 swift 中使用 NSLayoutConstraint 根据屏幕尺寸更改设计

标签 swift iphone storyboard size nslayoutconstraint

我使用 iPhone XR 的 Storyboard约束设计了一个屏幕,但该设计在 iPhone7 中变得很大,因此我想使用 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 类方法 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) }
}

关于swift - 如何在 swift 中使用 NSLayoutConstraint 根据屏幕尺寸更改设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58320775/

相关文章:

ios - @available - 仅在 OS X 上可用

swift - 这个 Singleton 对象可以在 Swift2 中使用类型存储属性吗?

arrays - 用于填充 SWIFT 中 Tableview 部分的结构体和数组

ios - textview的文本在textview下重叠

iphone - 如何以编程方式确定 iPhone 上的默认铃声?

ios - 从 Storyboard 加载 Collection View Cell(而不是从带有 registerNib 的 nib)

ios - 具有多个类的 Storyboard UIViewController

ios - 以编程方式同时关闭 UINavigation View 和模态视图

iphone - UIView层addAnimation :forKey:

iphone - iphone 是否可以一次在一个屏幕上设置多个tableview