【问题标题】:How to load a specific storyboard depending on size of screen如何根据屏幕大小加载特定的故事板
【发布时间】:2015-03-22 20:58:17
【问题描述】:

我正在尝试开发一个与 3.5 英寸和 4 英寸显示器兼容的应用程序。但是,当我尝试使用自动布局时,我无法弄清楚如何根据屏幕大小调整视图大小。我能想到的唯一另一种方法是设计两个故事板并根据手机屏幕的大小加载一个。有人可以帮我解决这个问题吗?谢谢你的时间。

【问题讨论】:

    标签: ios xcode autolayout uistoryboard


    【解决方案1】:

    AutoLayout 无法针对特定型号的 iPhone。但是,有一个解决方法。你有两个选择。

    第一个选项

    放置一个不可见的UIView 并使用Superview 创建顶部、底部、前导和尾随约束。之后,将您的对象(它们可以是 UIImageViewsUILabels 等等)放在您刚刚放置的 UIView 中。现在创建将您的对象连接到UIView 的顶部和底部约束。

    我创建了一个演示来向您展示它是如何完成的。正如您将看到的,按钮具有不同的大小,具体取决于屏幕的大小。从this 链接下载演示。

    第二个选项

    您可以通过编程方式创建和修改约束。创建一个NSLayoutConstraint 并根据用户的设备调整它的constant

    var myConstant: CGFloat = 0
    
    if UIScreen.mainScreen().bounds.size.height == 480 {
            // iPhone 4
        myConstant = 10
        } else if UIScreen.mainScreen().bounds.size.height == 568 {
            // iPhone 5
        myConstant = 20
        } else if UIScreen.mainScreen().bounds.size.width == 375 {
            // iPhone 6
        myConstant = 30
        } else if UIScreen.mainScreen().bounds.size.width == 414 {
            // iPhone 6+
        myConstant = 40
        } else if UIScreen.mainScreen().bounds.size.width == 768 {
            // iPad
        myConstant = 50
        }
    
    var myConstraint = NSLayoutConstraint (item: myButton,
            attribute: NSLayoutAttribute.Top,
            relatedBy: NSLayoutRelation.Equal,
            toItem: self.view,
            attribute: NSLayoutAttribute.Top,
            multiplier: 1,
            constant: myConstant)
        self.view.addConstraint(myConstraint)
    

    【讨论】:

      【解决方案2】:

      查看故事板上的size classes。您可以指定相同组件的其他布局,在不同设备上使用相同的代码。

      如果你真的想使用不同的故事板,请在 AppDelegate 中的方法application:didFinishLaunchingWithOptions: 中设置它。在这里你可以得到屏幕尺寸

      self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
      

      并使用

      设置情节提要
      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      window!.rootViewController = storyboard.instantiateViewControllerWithIdentifier("InitVC") as UIViewController
      window!.makeKeyAndVisible()
      

      此代码将使用故事板Main 和初始视图控制器InitVC 实例化应用程序

      【讨论】:

        猜你喜欢
        • 2017-06-13
        • 2015-02-15
        • 2021-01-04
        • 1970-01-01
        • 2019-11-07
        • 2014-03-30
        • 2013-10-26
        • 2018-11-27
        • 2018-02-07
        相关资源
        最近更新 更多