Conditional Compilation seems to be not working in Xamarin Studio

拟墨画扇 提交于 2019-12-10 21:15:39

问题


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)

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.


回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/43638339/conditional-compilation-seems-to-be-not-working-in-xamarin-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!