Xamarin.Forms is gaining momentum in the
Xamarin world. It allows you to build beautiful, performant native apps for iOS, Android, and Windows. You create pages and views code once and have them rendered natively on all targeted platforms.
If you have dealt with
iOS before, you are certainly aware of the feature that was introduce beginning iOS7: A single-page application shares the screen with the status bar.
That means that the top of the displayed page will occupy the same space at the status bar, unless the application specifically compensate for it with extra padding. This extra padding at the top is however only required for iOS since Android and Windows Phone do not have this issue.
Instead of defining a
Shared Asset Project with conditional compilation (very ugly in my opinion, please never use it!),
Xamarin.Forms provides two methods on the static class
OnPlatform which allows you to execute code specific to a particular platform from your shared code! How amazing is that?
- The first method
Device.OnPlatform<T>takes 3 arguments of type T, one for each platform. Using the named parameter feature introduce in C#4, you could write the following to set the padding on iOS only
- The second method
Device.OnPlatformtakes 4 optional arguments of type action, one for each platform plus the default action to be called if no platform specific action is provided. Our adjustment for padding would look something like
In this variation, we are only executing an action if the target platform is
Device.OnPlatform method is a very neat tool to tweak the UI depending on the target platform. However it does not have access to platform specific APIs.
For that, the use of
dependency injection is the way to go!