Reputation: 554
I am trying to develop an app to be compatible with the 3.5 inch as well as the 4 inch displays. However when I try to use auto layout I can not figure out how to resize the views depending on the size of the screen. The only other way I can imagine going around this is to design two storyboards and load one depending on the size of the screen of the phone. Can someone help me out with this? Thanks for your time.
Upvotes: 1
Views: 549
Reputation: 9419
AutoLayout can't target specific models of iPhone. However, there is a workaround for that. You have two options.
Place an invisible UIView
and create top, bottom, leading and trailing constraints come ted with the Superview
. After that place your objects (they can be UIImageViews
, UILabels
and the list goes on) inside the UIView
you have just placed. Now create top and bottom constraints that connect your objects to the UIView
.
I created a demo to show you how it's done. As you will see, buttons have different sizes depending on the screen's size. Download the demo from this link.
You could create and modify constraints programmatically. Create a NSLayoutConstraint
and adjust the constant
of it depending on the user's device:
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)
Upvotes: 1
Reputation: 14340
Check out size classes on the storyboard. You can specify other layouts of the same components, using the same code on different devices.
If you really want to use different storyboards, set it in AppDelegate in the method application:didFinishLaunchingWithOptions:
. Here you can get the screen size by
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
and set the storyboard using
let storyboard = UIStoryboard(name: "Main", bundle: nil)
window!.rootViewController = storyboard.instantiateViewControllerWithIdentifier("InitVC") as UIViewController
window!.makeKeyAndVisible()
This code will instantiate the app with the storyboard Main
and the initial view controller InitVC
Upvotes: 0