Conditional Compilation seems to be not working in Xamarin Studio
Asked Answered
H

2

5

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.

Harlin answered 26/4, 2017 at 15:22 Comment(0)
K
2

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/

Knuckleduster answered 26/4, 2017 at 15:35 Comment(1)
This is the way to go if you are using Xamarin Forms versions before v2.3.4. Otherwise, use Device.RuntimePlatform as I stated in my answer.Camporee
C
9

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.

Camporee answered 27/4, 2017 at 9:9 Comment(0)
K
2

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/

Knuckleduster answered 26/4, 2017 at 15:35 Comment(1)
This is the way to go if you are using Xamarin Forms versions before v2.3.4. Otherwise, use Device.RuntimePlatform as I stated in my answer.Camporee

© 2022 - 2024 — McMap. All rights reserved.