Search code examples
iosswiftautolayoutstoryboardxib

How to make 1 IBOutlet works for different devices?


Say I got a general iPhone size and iPad size to work out.

The iPad has a UIButton that links to UIViewController as a IBOutlet. Whereas iPhone doesn't need this UIButton but since iPhone and iPad all in 1 Storyboard and any other IBOutlet are identical. What is the most proper way to deal with this?

What I am thinking is to make the @IBOutlet weak var button:UIButton? optional and only the iPad's button links to it. But every action I do in the code requires button?.xxxxx

Any suggestions?


Solution

  • Don't change the layout depending on device. Apple now starts using size classes to describe their devices. Currently, iPads all have a horizontal size class of "Regular" and a vertical size class of "Regular" when in full screen (it's different when you do multitasking on an iPad).

    Select your button and go to the properties inspector. Scroll down and you'll find this "Installed" property:

    enter image description here

    Click on the "+" sign and this should appear:

    enter image description here

    Select "Regular" for both "width" and "height". Now you should see two "Installed" properties - one for wRhR and one for everything else. Just uncheck the one for everything else to only have the button on iPads.

    enter image description here

    Now you need to be careful in code. As your button can be nil on a phone. Remember to do nil checks!