Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Richard Rodriguez
Richard Rodriguez
2,687 Points

Device Specific Code?

How do i write code that will be implemented only if the user is using a specific device. For example, if the user is using an iPhone 4 i want an image to have an Xscale of .5 and if the user has an iPhone 6 I want the image xscale of .8

1 Answer

Michael Hulet
Michael Hulet
47,842 Points

WARNING: The method described here is untested, and was entirely formulated while I was writing this answer. It gets tedious for running code conditionally on a lot of devices, and I don't guarantee it works, as it's entirely untested

Apple doesn't give a clear-cut way to check for specific devices. Off the top of my head, I suppose you could start out by detecting the device family (iPhone & iPod touch or iPad) by getting the current UIUserInterfaceIdiom with the following code:

//Possible values are UIUserInterfaceIdiomPad and UIUserInterfaceIdiomPhone
UIUserInterfaceIdiom currentIdiom = [UIDevice currentDevice].userInterfaceIdiom;

Then, you could get the size of the frame of the view of a currently-showing view controller, like this:

CGSize screenSize = [UIApplication sharedApplication].keyWindow.rootViewController.view.frame.size;

You could then figure out what device it is by comparing the size to known device sizes. For example, that size on an iPhone 4s would always be equal to the CGSize returned by CGSizeMake(320, 480); if the iPhone is portrait, or CGSizeMake(480, 320);, if it's landscape. So, in theory, you could conditionally run your code like this:

//For an iPhone 4s only, but the same logic will apply to others. You just need to figure out their size
if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone && (CGSizeEqualToSize([UIApplication sharedApplication].keyWindow.rootViewController.view.frame.size, CGSizeMake(480, 320)) || CGSizeEqualToSize([UIApplication sharedApplication].keyWindow.rootViewController.view.frame.size, CGSizeMake(320, 480)){
    //Run your iPhone 4s-only code here