OStack程序员社区-中国程序员成长平台

标题: ios - UIImage imageNamed : name returns nil the second time [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:03
标题: ios - UIImage imageNamed : name returns nil the second time

我有这段代码用来测试 iOS 中的动画。目标是加载 4 个 png 并在 UIImageView 中为它们设置动画。我有一个 NSMutableArray imageNames 在其中保存图像的路径。它被正确填充。然后,当我尝试使用它创建 UIImage 时,它第一次工作,但之后返回 nil。为什么会这样?我无法理解这一点。

for (NSInteger i = 0; i < imageNames.count; i++) {
    NSString *name = [imageNames objectAtIndex:i];
    [images addObject:[UIImage imageNamed:name]];
}

这是完整的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *test = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 50, 50)];
    test.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:test];
    self.view.backgroundColor = [UIColor greenColor];
    NSMutableArray *imageNames = [[NSMutableArray alloc] initWithCapacity:4];

    NSString *basePath = @"/Users/johndoe/Desktop/soa/SoA/SoA/Models/firefly/";
    // Load images
    for (NSInteger i = 0; i < 4; i++) {
        NSMutableString *fullPath = [NSMutableString stringWithString:basePath];
        [fullPath appendFormat"SMALL_0000_Capa-%ld.png", i + 1];
        [imageNames addObject:fullPath];
//        [fullPath appendString"SMALL_0000_Capa-1.png"];

    }

    NSMutableArray *images = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < imageNames.count; i++) {
        NSString *name = [imageNames objectAtIndex:i];
        [images addObject:[UIImage imageNamed:name]];
    }

    // Normal Animation
    UIImageView *animationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 95, 86, 193)];
    animationImageView.animationImages = images;
    animationImageView.animationDuration = 0.5;

    [self.view addSubview:animationImageView];
    [animationImageView startAnimating];
}



Best Answer-推荐答案


好吧,正如您所说,这是出于学习目的,我已经尝试了您的代码,我发现唯一真正的问题是@rmaddy 指出的问题。我不知道您的图像的确切存储位置,但我尝试将 4 个图像添加为 Assets 并从此更改您的代码:

NSString *basePath = @"/Users/johndoe/Desktop/soa/SoA/SoA/Models/firefly/";
// Load images
for (NSInteger i = 0; i < 4; i++) {
    NSMutableString *fullPath = [NSMutableString stringWithString:basePath];
    [fullPath appendFormat"SMALL_0000_Capa-%ld.png", i + 1];
    [imageNames addObject:fullPath];
}

到这里:

// Load images
for (NSInteger i = 0; i < 4; i++) {
    NSString *path = [NSString stringWithFormat"pos%i", i];
    [imageNames addObject:path];
}

我认为它按您的预期工作。

关于ios - UIImage imageNamed : name returns nil the second time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185479/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4