1

现在 Xcode 5 有没有一种聪明的方法可以在你的应用程序中加载不同的图像,这取决于它是否是 iOS7?

我能想出的最佳解决方案是在 iOS7 所需图像的末尾附加“_7”,然后在应用程序中使用图像时,我可以:

NSString *OSSuffix = OSVersion == 7 ? @"_7" : @""; //would be define globally, also pseudo syntax
[UIImage imageNamed:[NSString stringWithFormat:@"imageName%@", OSSuffix]]; //can make a macro for this probably

但是有没有更好的更“内置”的方式来使用新的资产目录或其他东西呢?

4

1 回答 1

2

我想知道一个类似的用例,根据设备类型自动加载 568 像素高的图像。由于没有提供该功能,我想出了一个补丁UIImage在 GitHub 上有一个示例项目

+ (void) load
{
    if  (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPhone) {
        // Running on iPad, nothing to change.
        return;
    }

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    BOOL tallDevice = (screenBounds.size.height > 480);
    if (!tallDevice) {
        // Running on a 320✕480 device, nothing to change.
        return;
    }

    method_exchangeImplementations(
        class_getClassMethod(self, @selector(imageNamed:)),
        class_getClassMethod(self, @selector(imageNamedH568:))
    );
}

// Note that calling +imageNamedH568: here is not a recursive call,
// since we have exchanged the method implementations for +imageNamed:
// and +imageNamedH568: above.
+ (UIImage*) imageNamedH568: (NSString*) imageName
{
    NSString *tallImageName = [imageName stringByAppendingString:@"-568h@2x"];
    NSString *tallImagePath = [[NSBundle mainBundle] pathForResource:tallImageName ofType:@"png"];
    if (tallImagePath != nil) {
        // Tall image found, let’s use it. We just have to pass the
        // image name without the @2x suffix to get the correct scale.
        imageName = [imageName stringByAppendingString:@"-568h"];
    }
    return [UIImage imageNamedH568:imageName];
}

您可以使用相同的技巧根据一些自定义名称标签自动加载 iOS 7 资源。同样的警告也适用:该UIImage技巧使用方法混合,并且可能在生产中具有太多的魔力。你的来电。

于 2013-10-30T07:47:39.307 回答