在 Watch 应用程序使用的文件中有条件地使用 UIKit

Use UIKit conditionally in file used by Watch app

我创建了一个模型 class,我在我的 iOS 应用程序和我的 Watch 应用程序中使用它 - 它包含在两个目标中。现在我必须在这个 class 中使用 UIPasteboard,它仅在 UIKit 中可用,而 watchOS 不可用。虽然我可以毫无问题地将 UIKit 导入此文件,但当我开始使用 UIPasteboard 时,它不会编译,因为 watch 扩展不知道它。

如何在手表应用可用的 class 中使用 UIPasteboard

我想知道当设备不是 Apple Watch 时我是否只能 运行 使用 #available 编写该代码,但这并没有解决问题。

if #available(iOS 7.0, *) {
    UIPasteboard.generalPasteboard()...
    //ERROR: Use of unresolved identifier 'UIPasteboard'
} else {
    //don't use UIPasteboard
}

也许您可以使用 扩展名 分解出 UIPasteboard 功能,并将仅包含扩展名的文件包含在 iPhone 目标中。

理想情况下,多个 OS 共享的代码应该只包含真正共享的代码。

此外,如果您想要条件性, 可能是一种更简洁的方法。

使用 Swift 中定义的现有预处理器指令:

#if os(iOS)
//UIKit code here
#elseif os(watchOS)
//Watch code here
#endif

请参阅预处理器指令的文档here

有两种方法。

第一种方法是使用预处理器指令,如下例所示:

#if os(iOS)
    //Insert UIKit (iOS) code here
#elseif os(watchOS)
    //Insert WatchKit (watchOS) code here
#endif

第二种方式是判断代码是从WatchKit Extension还是iOSApp调用的。例如,您可以在从 WatchKit Extension 调用代码之前将全局布尔标志设置为 true,在从 iOS App 调用代码之前将其设置为 false。然后共享代码可以检查标志的值以确定它在 iOS 或 watchOS.

上是 运行