Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Compilation seems to be not working in Xamarin Studio

I created a Xamarin Forms app. And inside a new page with a label named "MyLabel". In the code behind for my page I have

private void SetUpUI()
{
    #if __IOS__
    this.MyLabel.BackgroundColor = Color.Navy;
    #endif
}

In my iOS project options I can see symbol __IOS__ in the "Compiler" tab. (please see screenshot)

enter image description here

When I run in iOS it doesn't make the label blue:

But if I remove #if __IOS__ block it makes the label blue:

So it seems conditional compilation is not working. I'm on a Mac. So couldn't test on Visual Studio. Stuck with it for a long time but cannot figure out what I missed.

like image 495
Koushik Sarkar Avatar asked Apr 26 '17 15:04

Koushik Sarkar


2 Answers

The answer of SushiHangover is correct: your PCL project won't have the compiler definitions for the platforms.

However, the solution he provides has become obsolete since Xamarin Forms 2.3.4 was released. Device.OnPlatform has been redesigned as discussed in this discussion and implemented in this Pull Request.

The correct way to do this in Xamarin Forms 2.3.4 and onwards is by using Device.RuntimePlatform. Use a switch or conditional to suit your needs like so:

if(Device.RuntimePlatform == Device.iOS)
{
    // iOS
}
else if(Device.RuntimePlatform == Device.Android)
{
    // Android
}

It would be possible to do it like you asked, if you were to use a shared project instead of a PCL. Because when you use a shared project, you have access to the compiler directives of your platform projects.

like image 155
Tim Klingeleers Avatar answered Nov 15 '22 09:11

Tim Klingeleers


You are using the conditionals in your PCL project which would not contain those compiler defines, thus why your conditional code is greyed out.

In your PCL project you can use Device.OnPlatform to perform platform based processing:

Device.OnPlatform (iOS: () => this.MyLabel.BackgroundColor = Color.Navy; );

re: https://developer.xamarin.com/api/member/Xamarin.Forms.Device.OnPlatform/

like image 20
SushiHangover Avatar answered Nov 15 '22 10:11

SushiHangover