Identifying what OS you’re app is being presented
If you ever have adventured yourself using
SwifUI you must certainly know how powerful it can be for making it a lot easier to create interactive and reactive UI, but jumping a step forward you can use SwiftUI on multiple platforms and but it’s pretty much obvious you can't wright the same UI rules for all of them.
With that being said, I’ll show you a quick solution to localize yourself inside the code and decide where to put certain rules for each platform you want your app to support.
Straightforward Code Time!
So, if you don’t know, UIKit isn’t apart of macOS development, so if you’re developing universally you need to do some workaround to exclude iOS related libraries at compile-time and for this, we use some Swift Compiler Directives to avoid compiler issues. In the example below, we’re using the
#endif to check if the current OS isn't macOS, so we can import UIKit.
But why we’re doing this? Here is the answer, simply to access
UIDevice.current.userInterfaceIdiom this is the class that will help us to identify between iPad and iPhone. So as we learned in the previous step to identify macOS, you're all set!
Just to wrap things up, in our ContentView we’re creating a device variable containing the iOS device type, inside the body, we using a swift compiler directive to separate between iOS and macOS. Within the iOS statement, we’re doing a simple if statement for iPhone and iPad, and we’re done! If you create a universal application, copy and paste type this code on your own content view and run it on each platform the result will look something like this…
Thank you for reading 😊