【问题标题】:How to change design according to screen size using NSLayoutConstraint in swift如何在 swift 中使用 NSLayoutConstraint 根据屏幕大小更改设计
【发布时间】:2020-02-07 18:32:40
【问题描述】:

我为 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
}

不幸的是,我对尺寸等级知之甚少。

【问题讨论】:

  • 对不起,我很困惑,你想在这里问什么? @swift
  • @jacob 在故事板中设计屏幕时,我已经为 iphonexr 中的 containerView 提供了前导、尾随、顶部、高度约束......但是该视图在剩余的 iphone 尺寸中占据了更多空间,所以我想改变它高度根据 iphone 尺寸
  • 不要使用常量约束,如果您希望它们根据屏幕大小而变化,请使用相对约束。
  • 所以让我们为您的前导和尾随制作插座参考以调整宽度,然后检查以按设备类型更新常量。我建议您应该根据视图宽度的百分比更改常量。
  • @jacob 我能够获得正确的宽度 bcs 我已经给出了前导和尾随但根据设备类型的高度问题..我们如何根据设备类型更改常量值...任何代码为此??

标签: swift iphone storyboard size nslayoutconstraint


【解决方案1】:

你可以随时向UIScreen类方法main询问当前的具体尺寸,它返回当前设备的具体尺寸。

let deviceSize = UIScreen.main.bounds.size

但您可能知道,heightwidth 会根据设备的方向(横向或纵向)而变化。

也许这个扩展会有所帮助:

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) }
}

【讨论】:

    【解决方案2】:

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

    例如:如果UIScreen.main.bounds.height 给你 1000。而你的容器高度是 400。那么所需的容器高度与屏幕高度的比率是 400/1000 或 2/5。

    现在,你能做的就是写

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多