4

我正在调试未显示 imageView 的问题。

imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
NSLog(@"imageView right after initialization is: %@", imageView);

imageView.frame = CGRectMake(2, 0, 316, 45);
imageView.layer.zPosition = zPos;
NSLog(@"imageView after running the setters: %@", imageView);

[self.view addSubview:imageView];

奇怪的是,有时imageView会显示,有时不会(大约 75% 的时间显示)。

imageView除了上面的代码外,在任何地方都无法访问。

我注意到的是,当imageView 不显示时,第一个日志语句显示:

初始化后的imageView是: <UIImageView: 0x9eaa760; 帧 = (0 0; 0 0); 用户交互启用 = 否;层 = <CALayer: 0x9ec04a0>>

显示图像视图时:

初始化后的imageView是: <UIImageView: 0xaa61ad0; 帧 = (0 0; 644 88); 不透明=否;用户交互启用 = 否;层=<CALayer:0xaa61330&rt;&rt;

已编辑:我进行了数十次测试,imageView 的行为始终相同:未显示时,初始帧为 (0 0; 0 0)。当它不是时,它总是一些其他的价值。

PS我没有使用ARC。

4

3 回答 3

2

UIImageView它显示的日志中frame = (0 0; 0 0);这意味着视图不会显示,因为它的高度和宽度为 0。这表明图像没有大小或者是nil.

造成这种情况的原因很可能是因为找不到您尝试加载的图像:您应该检查是否找到了图像:

UIImage *image = [UIImage imageNamed:imageName];
if (!image) {
   NSLog(@"Image could not be found: %@", imageName);
}

imageView = [[UIImageView alloc] initWithImage:image];

这意味着即使您更改框架,您仍然看不到任何内容,因为没有加载图像。

于 2013-09-09T09:01:26.167 回答
2

为什么不先设置框架,然后设置图像?

 imageView = [UIImageView alloc]initWithFrame:CGRectMake(0,0,35,35)];
 [imageView setImage:[UIImage imageNamed:@"img.png"]];
于 2013-09-09T08:57:59.930 回答
1

除了rckoenes 答案之外, 您必须始终首先检查图像是否存在于您的捆绑路径中:

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory 
        = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
             objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:imageName];
    if([fileManager fileExistsAtPath:path])
    {
       UIImage *image = [UIImage imageNamed:imageName];
       if (!image) {
          NSLog(@"Image could not be found: %@", imageName);
       }

       imageView = [[UIImageView alloc] initWithImage:image];
    } else {
       NSLog(@"%@ is not included in the app file bundle!", imageName);
    }

这样你就会知道问题是否是 b/c 你首先没有文件.. 或者 b/c 文件有问题阻止 iOS 加载它。

于 2013-09-09T09:36:56.937 回答