2013-10-21 136 views
0

所以我想子视图(的UIImageView)添加到我的主要观点有以下代码:设置子视图的初始位置

NSString *fileLocation = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"background_main.png"]; 
_aImage = [[UIImage alloc] initWithContentsOfFile:fileLocation]; 
_aImageView = [[UIImageView alloc] initWithImage:_aImage]; 
_aImageView.frame = CGRectMake(-200, 0, _aImage.size.width, _aImage.size.height); 
[self.view addSubview:_aImageView]; 

,你可以看到 - 我加入的UIImageView到位置(-200 ; 0);

但它显示在默认位置:(0; 0)。

我的视图层次:

  1. self.view -main视图,其中我添加子视图(的UIImageView);
  2. _aImageView - 我添加的UIImageView。

结果:

NSLog(@"image is %@",_aImageView); //result (-200 0; 420 568) 

CGPoint test = [_aImageView convertPoint:_aImageView.frame.origin toView:self.view]; 
NSLog(@"convert %f %f",test.x,test.y); //result (-400.000000; 0.000000) 

我知道那个位置仍然是(0,0),因为我可以看到它时,我测试我的应用程序。后来当我将_aImageView的位置更改为(-50; 0)时,它显示黑屏。我知道我错过了一些非常重要的东西,但我无法弄清楚为什么它出现在(0; 0)的位置。

链接类似的问题,我已经检查:

+0

在哪个视图中的位置{0,0}。提供视图层次结构的一些细节以及如何测试结果值。 – Wain

回答

0

什么在过去的工作对我来说在这种情况下,做这样的事情:

NSString *fileLocation = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"background_main.png"]; 
_aImage = [[UIImage alloc] initWithContentsOfFile:fileLocation]; 
_aImageView = [[UIImageView alloc] initWithImage:CGRectMake(-200, 0, _aImage.size.width, _aImage.size.height)]; 
[_aImageView setImage:_aImage]; 
[self.view addSubview:_aImageView]; 

如果这不起作用尝试改变它在viewDidAppear方法(我假设你在viewDidLoad中添加它)框架。

最后一种解决方案是在将视图添加到屏幕后设置视图的中心。

CGPoint pt=CGPointMake(-200+_aImageView.frame.size.width/2,_aImageView.frame.size.height/2); 
_aImageView.center=pt; 

如果失败,视图在代码的另一部分中被更改,或者视图正确添加在屏幕上,但图像为零。

+0

有趣的是,当我使用init代码我设置帧和图像。通过设置图像,一切正常,但无论我设置的是什么框架,都始终默认大小和位置。 – ignotusverum

+0

谢谢,我只是需要休息,已经修复:) – ignotusverum

+0

虽然你的帖子是非常有用的! – ignotusverum

0

我相信你无法改变帧直到layoutSubviews。您可以设置在layoutSubviews框架...

-(void)layoutSubviews 
{ 
    [_aImageView setFrame:CGRectMake(-200, 0, _aImage.size.width, _aImage.size.height)]; 
} 

还是第一次设置帧再加入无论你正在初始化的UIImageView图像...

_aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-200, 0, _aImage.size.width, _aImage.size.height]; 
[_aImageView setImage:_aImage]; 
+0

没有任何变化,谢谢 – ignotusverum