是否可以根据 SDK 版本隐藏代码

Is it possible to hide code based on SDK version

提问人:ximmyxiao 提问时间:8/16/2021 最后编辑:ximmyxiao 更新时间:10/15/2021 访问量:811

问:

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

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

评论

0赞 Phil Dukhov 8/16/2021
不,这是不可能的

答:

5赞 Michi 8/26/2021 #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 中构建时被省略。👍

评论

0赞 ximmyxiao 9/29/2021
很棒的解决方案,谢谢@Michi
3赞 palme 10/15/2021 #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