快速可用性检查不包括macOS

问题描述 投票:0回答:1

我的应用程序中有一个代码,我想在iOS 13或更高版本上执行。因此,我正在使用标准的可用性检查:

if #available(iOS 13.0, *) {
    return Color.systemGray6.resolvedColor(with: trait!)
} else {
    return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
}

Color是一种类型别名,在iOS上转换为UIColor,在macOS上转换为NSColor。我有点想用最少的if..else创建目标的macOS版本。

上面的代码应该与NSColor一起使用,具有许多与UIColor相同的初始化方法。问题是,当我构建我的macOS目标时,它抱怨systemGray6。因此,出于我未知的原因,macOS目标通过了#available(iOS 13.0, *)检查!

为什么会发生,如何预防?

ios swift macos conditional-compilation
1个回答
1
投票

[当您使用if #available(iOS 13.0, *)时,您基本上是说:在iOS 13.0及更高版本上执行此操作,以及在所有其他操作系统上-这就是*的意思。

在您的特定情况下,您需要排除macOS,因为NSColor没有systemGrayX吸气剂:

#if os(iOS)
if #available(iOS 13.0, *) {
     return Color.systemGray6
}
#endif
return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
© www.soinside.com 2019 - 2024. All rights reserved.