条件编译似乎在 Xamarin Studio 中不起作用
Conditional Compilation seems to be not working in Xamarin Studio
我创建了一个 Xamarin Forms 应用程序。
在一个名为 "MyLabel" 的标签的新页面中。
在我的页面后面的代码中,我有
private void SetUpUI()
{
#if __IOS__
this.MyLabel.BackgroundColor = Color.Navy;
#endif
}
在我的 iOS 项目选项中,我可以在 "Compiler" 选项卡中看到符号 __IOS__
。 (请看截图)
当我在 iOS 中 运行 时,它不会使标签变成蓝色:
但如果我删除 #if __IOS__
块,它会使标签变为蓝色:
所以条件编译似乎不起作用。
我在 Mac。所以无法在 Visual Studio 上进行测试。
坚持了很长时间,但无法弄清楚我错过了什么。
您在 PCL 项目 中使用了不包含那些编译器定义的条件,因此您的条件代码 变灰出.
在您的 PCL 项目中,您可以使用 Device.OnPlatform
执行基于平台的处理:
Device.OnPlatform (iOS: () => this.MyLabel.BackgroundColor = Color.Navy; );
回复:https://developer.xamarin.com/api/member/Xamarin.Forms.Device.OnPlatform/
SushiHangover 的回答是正确的:您的 PCL 项目 将没有平台的编译器定义。
但是,他提供的解决方案自Xamarin Forms 2.3.4 发布以来就已经过时了。 Device.OnPlatform 已按照 this discussion and implemented in this Pull Request 中的讨论进行了重新设计。
在 Xamarin Forms 2.3.4 及更高版本中执行此操作的正确方法是使用 Device.RuntimePlatform
。使用开关或条件来满足您的需求,如下所示:
if(Device.RuntimePlatform == Device.iOS)
{
// iOS
}
else if(Device.RuntimePlatform == Device.Android)
{
// Android
}
如果您要使用 共享项目 而不是 PCL,则可以按照您的要求进行操作。因为当您使用共享项目时,您可以访问平台项目的编译器指令。
我创建了一个 Xamarin Forms 应用程序。 在一个名为 "MyLabel" 的标签的新页面中。 在我的页面后面的代码中,我有
private void SetUpUI()
{
#if __IOS__
this.MyLabel.BackgroundColor = Color.Navy;
#endif
}
在我的 iOS 项目选项中,我可以在 "Compiler" 选项卡中看到符号 __IOS__
。 (请看截图)
当我在 iOS 中 运行 时,它不会使标签变成蓝色:
但如果我删除 #if __IOS__
块,它会使标签变为蓝色:
所以条件编译似乎不起作用。 我在 Mac。所以无法在 Visual Studio 上进行测试。 坚持了很长时间,但无法弄清楚我错过了什么。
您在 PCL 项目 中使用了不包含那些编译器定义的条件,因此您的条件代码 变灰出.
在您的 PCL 项目中,您可以使用 Device.OnPlatform
执行基于平台的处理:
Device.OnPlatform (iOS: () => this.MyLabel.BackgroundColor = Color.Navy; );
回复:https://developer.xamarin.com/api/member/Xamarin.Forms.Device.OnPlatform/
SushiHangover 的回答是正确的:您的 PCL 项目 将没有平台的编译器定义。
但是,他提供的解决方案自Xamarin Forms 2.3.4 发布以来就已经过时了。 Device.OnPlatform 已按照 this discussion and implemented in this Pull Request 中的讨论进行了重新设计。
在 Xamarin Forms 2.3.4 及更高版本中执行此操作的正确方法是使用 Device.RuntimePlatform
。使用开关或条件来满足您的需求,如下所示:
if(Device.RuntimePlatform == Device.iOS)
{
// iOS
}
else if(Device.RuntimePlatform == Device.Android)
{
// Android
}
如果您要使用 共享项目 而不是 PCL,则可以按照您的要求进行操作。因为当您使用共享项目时,您可以访问平台项目的编译器指令。