我有一个UIImageView
我无法获取图片并设置显示。
viewDidLoad
中的
albumContainer = [[UIImageView alloc]initWithFrame:CGRectMake(112, 7, 97, 97)];
[self.view addSubview:albumContainer];
从不同的类调用方法
NSLog(@"URL:%@",url);
//URL is defined by different class
//URL is http://www.....882546328.jpg (I abbreviated it, but it is a valid url)
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSLog(@"URL LENGTH:%d",[imageData length]);
// URL LENGTH:90158
UIImage *tempImage = [UIImage imageWithData:imageData];
[albumContainer setImage:tempImage];
完整代码
PlayerViewController
-(void)viewDidLoad{
[super viewDidLoad];
playerView = [[AlbumViewController alloc]initWithNibName:@"AlbumViewController" bundle:nil];
}
-(void)playMusic{
playerView.url = [NSURL URLWithString:imagePathForm];
playerView.songData = receivedData;
[loadingSong stopAnimating];
[playerView play];
}
AlbumViewController
- (void)viewDidLoad
{
[super viewDidLoad];
albumContainer = [[UIImageView alloc]initWithFrame:CGRectMake(112, 7, 97, 97)];
[self.view addSubview:albumContainer];
url = [NSURL URLWithString:@""];
}
-(void)play{
NSLog(@"SONGDATA:%d",[songData length]);
player = [[AVAudioPlayer alloc] initWithData:songData error: nil];
[player stop];
player.delegate = self;
player.numberOfLoops = 0;
player.volume = 0.5;
[player prepareToPlay];
[player play];
NSLog(@"URL:%@",url);
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSLog(@"URL LENGTH:%d",[imageData length]);
UIImage *tempImage = [UIImage imageWithData:imageData];
[albumContainer setImage:tempImage];
}
我检查过,albumContainer记录为NULL
答案 0 :(得分:1)
在设置图像之前,您是否检查过控制器的视图已加载? UIViewControllers在显示之前不加载它们的视图,并且它们有时会在屏幕外卸载它,因此当你调用
时可能没有调用viewDidLoad。[albumContainer setImage:tempImage];
从控制器外部。在设置图像之前尝试记录albumContainer以查看它是否为零,如下所示:
NSLog(@"albumContainer: %@", albumContainer); //might log as null
[albumContainer setImage:tempImage];
要强制加载控制器的视图,您可以说:
[controller view]; // this will load the view and call viewDidLoad
[albumContainer setImage:tempImage];
但是你可能最好在initWithNibName:bundle:view中创建你的albumContainer,而不是在viewDidLoad中,如下所示:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)bundleOrNil
{
if ((self = [super initWithNibName:nibNameOrNil bundle:bundleOrNil]))
{
albumContainer = [[UIImageView alloc]initWithFrame:CGRectMake(112, 7, 97, 97)];
[self.view addSubview:albumContainer];
}
return self;
}
这样即使视图尚未加载,它也会与控制器同时创建。