【问题标题】:How to conditionally compile for tvOS in Swift如何在 Swift 中为 tvOS 有条件地编译
【发布时间】:2016-02-04 13:10:42
【问题描述】:

如何在 Swift 语言的同一个文件中有条件地编译 iOS 和 tvOS 的代码? 我已经尝试了 Apple 文档中提到的 TARGET_OS_TV 的所有 Objective-C 样式 #if 等,以及其他一些答案。但我还没有找到适用于 Swift 代码的有效解决方案。

【问题讨论】:

  • 这应该可以工作#if TARGET_OS_TV NSLog(@"tVOS"); #else NSLog(@"不是 iOS"); #endif

标签: ios swift tvos


【解决方案1】:
#if os(OSX)
// compiles for OS X
#elseif os(iOS)
// compiles for iOS
#elseif os(tvOS)
// compiles for TV OS
#elseif os(watchOS)
// compiles for Apple watch
#endif

【讨论】:

  • 谢谢。对我来说清楚的例子。
  • 欢迎@Pop。如果你能接受你喜欢的答案,那就太好了:)谢谢!
  • CarPlay 的操作系统是什么
【解决方案2】:

Apple 在标题 Targeting Apple TV in Your Apps 下也涵盖了这一点

清单 1-1 Objective-C 中 tvOS 的条件化代码

 #if TARGET_OS_TV
     NSLog(@"Code compiled only when building for tvOS.");
 #endif

清单 1-2 Swift 中 tvOS 的条件化代码

#if os(tvOS)
NSLog(@"Code compiled only when building for tvOS.");
#endif

if #available(tvOS 9.1,*) {
    print("Code that executes only on tvOS 9.1 or later.")
}

【讨论】:

  • 非常有助于了解 Objective-C 和 Swift 语法之间的差异。
【解决方案3】:
#if <build configuration> && !<build configuration>
statements
#elseif <build configuration>
statements
#else
statements
#endif

构建配置可以在哪里:-
os(abc) 其中 abc 的有效值为 OSX、iOS、watchOS、tvOS、Linux
arch(abc) 其中 abc 的有效值为 x86_64、arm、arm64、i386

请参阅 Apple 文档here

【讨论】:

    【解决方案4】:

    我没有文档参考——虽然我想要一个——但我看到了 Apple 示例代码,其中包含以下部分:

        #if os(iOS) || os(tvOS)
        #endif
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2015-06-08
      • 2017-10-06
      • 2020-02-06
      • 2013-06-08
      • 2012-08-07
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多