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

时间:2015-08-16 19:58:58

标签: ios swift watchkit swift2 watch-os-2

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

如何在我的观看应用可用的课程中使用#available

我想知道如果使用if #available(iOS 7.0, *) { UIPasteboard.generalPasteboard()... //ERROR: Use of unresolved identifier 'UIPasteboard' } else { //don't use UIPasteboard } 设备不是Apple Watch,我是否只能运行该代码,但这并没有解决问题。

public class Circle {

    public static final double PI = 3.141592654;
    protected double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public String toString() {
        return "Class = " + getClass().getSimpleName() + " (radius = " + radius + ")";
    }
}


public class PlaneCircle extends Circle {

    private double centerX, centerY;

    public PlaneCircle(double radius, double centerX, double centerY) {
        super(radius);
        this.centerX = centerX;
        this.centerY = centerY;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}

3 个答案:

答案 0 :(得分:5)

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

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

请参阅预处理程序指令here的文档。

答案 1 :(得分:1)

有两种方法可以做到。

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

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

第二种方法是确定是否从WatchKit Extension或iOS App调用代码。例如,您可以在调用WatchKit Extension中的代码之前将全局布尔标志设置为true,并在从iOS App调用之前将false设置为group by。然后共享代码可以检查标志的值,以确定它在iOS或watchOS上运行。

答案 2 :(得分:0)

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

理想情况下,多个操作系统共享的代码应仅包含真正的共享代码。

此外,如果你想要条件,this可能是一种更清洁的方法。

相关问题