Search code examples
xamarinxamarin.iosxamarin.formsconditional-compilation

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.


Solution

  • 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/