In Xamarin.Forms, what is the common way to branch between IOS and ANDROID methods?

Issue

I am new to Xamarin.Forms. I think like a normal coder. If Android, do this… if Ios, do this…

In Xamarin Forms, say someone clicks a button which is binded to a view model, what is the common way to select a platform specific method between Android and IOS?

FYI, there are 3 projects in a Xamarin Solution

  • Project
  • Project.Android
  • Project.IOS

The View model is inside ‘Project’ >

 `private async void OnLoginClicked(object obj)
        {

           //If Android??

           //If IOS?
        }`

Solution

You can use Device class for this purpose. It has property RuntimePlatform to check current platform.

double top;
switch (Device.RuntimePlatform)
{
  case Device.iOS:
    top  20;
    break;
  case Device.Android:
  case Device.UWP:
  default:
    top  0;
    break;
}
layout.Margin  new Thickness(5, top, 5, 0);

More info : https://docs.microsoft.com/en-us/xamarin/xamarin-forms/platform/device

Answered By – Qwerty

Leave a Comment