【问题标题】:Override files in .xcassets覆盖 .xcassets 中的文件
【发布时间】:2014-05-30 11:31:09
【问题描述】:

我有一个带有多个目标的 iOS 应用。每个目标都有自己的 .xcassets 保存特定于该目标的图像,我还有一个基本 .xcassets 文件夹,其中保存在所有目标之间共享的图像。

基本 .xcassets 和目标 .xcassets 文件夹可能具有具有相同文件名的图像,但它们是不同的图像。当应用程序运行时,我希望 Xcode 使用来自目标 .xcassets 文件夹的图像,而不是来自基本 .xcassets 文件夹的图像。现在,当我在每个 .xcassets 文件夹中有两个具有相同文件名的不同图像时,我会收到编译器警告。当我运行应用程序时,它使用基础 .xcassets 文件夹中的图像。

有谁知道如何解决这个问题?我正在考虑编写某种 shell 脚本,但我想知道是否有更简单的方法。

【问题讨论】:

  • 如果您在构建阶段订购了.xcassets 文件夹,以使基础高于您要使用的那个文件夹,这行得通吗?
  • 这没有任何作用,不过谢谢。

标签: ios shell xcode5 assets


【解决方案1】:

不要对基础和目标使用相同的图像名称。它们之间的名称应该不同。我还专门针对这个多目标资产问题写了blog post

【讨论】:

  • 我知道名称应该不同,但在代码库中它正在寻找一个特定的图像。我有接近 20 个目标,每次我需要显示图像时检查正在运行的目标是低效的。每个目标都可能有一个自定义版本的图像,它位于基础中。如果它们没有相同的名称,我如何覆盖基础中的图像?我会看看你的博文。谢谢
  • 您不应该覆盖基础中的任何图像。您应该只有 2 个 xcasset 文件夹:一个包含所有目标中完全相同的图像,一个用于不同的图像。
  • 对于“大多数”目标相同但在一个或几个目标上不同的图像怎么办?唯一的解决方案是复制所有图像?
【解决方案2】:

我在白标应用程序结构中有这个要求。基础应用程序有一个完整的资产目录,每个特定的目标可能会覆盖一些资源。我最终调整了 UIImage 方法来寻找一个压倒一切的前缀。每个目标都应该将该前缀添加到它想要覆盖的资源名称中。从代码或 IB 加载图像时,swizzling 将加载覆盖的版本(如果存在)。

看起来像这样:

#import <JRSwizzle.h>

static NSString *_xcassetsOverridePrefix = @"override_";

static inline NSString* overridenName(NSString *name) {
    return [_xcassetsOverridePrefix stringByAppendingString:name];
}

@implementation UIImage (OverrideableXCAssets)

+(void)load {
    NSError *error;
    if (![self jr_swizzleClassMethod:@selector(imageNamed:) withClassMethod:@selector(imageNamedReplacement:) error:&error]) {
        NSLog(@"Error swizzling UIImage imageNamed: %@", [error localizedDescription]);
    }
    if (![self jr_swizzleClassMethod:@selector(imageNamed:inBundle:compatibleWithTraitCollection:) withClassMethod:@selector(imageNamedReplacement:inBundle:compatibleWithTraitCollection:) error:&error]) {
        NSLog(@"Error swizzling UIImage imageNamed: %@", [error localizedDescription]);
    }
}

+ (UIImage*)imageNamedReplacement:(NSString *)name {
    UIImage *image = [self imageNamedReplacement:overridenName(name)];
    if (!image) {
        image = [self imageNamedReplacement:name];
    }
    return image;
}

+ (UIImage*)imageNamedReplacement:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection {
    UIImage *image = [self imageNamedReplacement:overridenName(name) inBundle:bundle compatibleWithTraitCollection:traitCollection];
    if (!image) {
        image = [self imageNamedReplacement:name inBundle:bundle compatibleWithTraitCollection:traitCollection];
    }
    return image;
}

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 2011-06-06
    • 2015-06-10
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多