【发布时间】:2015-03-22 20:58:17
【问题描述】:
我正在尝试开发一个与 3.5 英寸和 4 英寸显示器兼容的应用程序。但是,当我尝试使用自动布局时,我无法弄清楚如何根据屏幕大小调整视图大小。我能想到的唯一另一种方法是设计两个故事板并根据手机屏幕的大小加载一个。有人可以帮我解决这个问题吗?谢谢你的时间。
【问题讨论】:
标签: ios xcode autolayout uistoryboard
我正在尝试开发一个与 3.5 英寸和 4 英寸显示器兼容的应用程序。但是,当我尝试使用自动布局时,我无法弄清楚如何根据屏幕大小调整视图大小。我能想到的唯一另一种方法是设计两个故事板并根据手机屏幕的大小加载一个。有人可以帮我解决这个问题吗?谢谢你的时间。
【问题讨论】:
标签: ios xcode autolayout uistoryboard
AutoLayout 无法针对特定型号的 iPhone。但是,有一个解决方法。你有两个选择。
放置一个不可见的UIView 并使用Superview 创建顶部、底部、前导和尾随约束。之后,将您的对象(它们可以是 UIImageViews、UILabels 等等)放在您刚刚放置的 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)
【讨论】:
查看故事板上的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 实例化应用程序
【讨论】: