【问题标题】:Is it possible to hide code based on SDK version是否可以根据 SDK 版本隐藏代码
【发布时间】:2021-08-16 06:19:11
【问题描述】:

因为我的构建机器仍在使用 Xcode 12.5,所以即使我使用 @available 来检查,UITabBar 的 scrollEdgeAppearance(Xcode 12.5 的 SDK 中不存在)也会导致构建失败。

if (@available(iOS 15.0, *)) {
    UINavigationBarAppearance* navBarAppearance = [UINavigationBarAppearance new];
    navBarAppearance.backgroundColor = [UIColor colorNamed:@"navbar_bg"];

    [UINavigationBar appearance].standardAppearance = navBarAppearance;
    [UINavigationBar appearance].scrollEdgeAppearance = navBarAppearance;
    
    UITabBarAppearance* tabBarAppearance = [UITabBarAppearance new];
    tabBarAppearance.backgroundColor = [UIColor colorNamed:@"second_bg"];
    [UITabBar appearance].standardAppearance = tabBarAppearance;
    [UITabBar appearance].scrollEdgeAppearance = tabBarAppearance;
    
    [UITableView appearance].sectionHeaderTopPadding = 0;
}

那么是否可以在代码中进行这种SDK检查,当构建的SDK不是最新的SDK时,这些代码将不会参与构建?像这样

if (BuilDSDK >= someversion) 
{
   [UITabBar appearance].scrollEdgeAppearance = tabBarAppearance;
}

【问题讨论】:

  • 不,不可能

标签: ios xcode xcodebuild


【解决方案1】:

@available 是一个运行时可用性检查,在这种情况下实际上不适用于编译时的东西。

在 Objective-C 中,您可以将应用在 iOS 15 SDK 上的代码部分包装到另一个宏条件中:

#ifdef __IPHONE_15_0
    if (@available(iOS 15.0, *)) {
        ...
    } else {
#endif
        // possible legacy branch code
#ifdef __IPHONE_15_0
    }
#endif

__IPHONE_15_0 是从 iOS 15 SDK 开始定义的,因此在 Xcode 12/iOS 14 SDK 中构建时被省略。 ?

【讨论】:

  • 很好的解决方案,感谢@Michi
【解决方案2】:

另一个类似的 Swift 类解决方案可以在这里找到:https://stackoverflow.com/a/69583441/1195661:

#if swift(>=5.5) // Only run on Xcode version >= 13 (Swift 5.5 was shipped first with Xcode 13).
        if #available(iOS 15.0, *) {
            UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
        }
#endif

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2018-07-16
    • 2013-09-16
    相关资源
    最近更新 更多