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

Jor*_*n H 4 ios swift watchkit swift2 watchos-2

我创建了一个我在iOS应用程序和Watch应用程序中使用的模型类 - 它包含在两个目标中.现在我必须UIPasteboard在这个只能使用的类中使用UIKit,这对watchOS是不可用的.虽然我可以毫无问题地将UIKit导入到这个文件中,但是当我使用UIPasteboard它时它将无法编译,因为手表扩展程序不知道它.

如何UIPasteboard在我的手表应用程序可用的类中使用?

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

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

Leo*_*ica 6

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

#if os(iOS)
//UIKit code here
#elseif os(watchOS)
//Watch code here
#endif
Run Code Online (Sandbox Code Playgroud)

请参阅此处的预处理程序指令文档.