我正在尝试开发一款兼容3.5英寸和4英寸显示屏的应用。但是,当我尝试使用自动布局时,我无法弄清楚如何根据屏幕大小调整视图大小。我能想象到的唯一另一种方法是设计两个故事板并根据手机屏幕的大小加载一个故事板。有人可以帮我解决这个问题吗?谢谢你的时间。
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
在故事板上查看size classes。您可以在不同设备上使用相同的代码指定相同组件的其他布局。
如果您真的想使用不同的故事板,请在方法application:didFinishLaunchingWithOptions:
中的AppDelegate中进行设置。在这里你可以通过
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