【问题标题】:Set initial position of subview设置子视图的初始位置
【发布时间】:2013-10-21 17:23:50
【问题描述】:

所以我想使用以下代码将子视图 (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 - 我要添加子视图的主视图(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}。详细说明您的视图层次结构以及您如何测试结果值。

标签: iphone ios objective-c


【解决方案1】:

过去在这种情况下对我有用的是做这样的事情:

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;

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

【讨论】:

  • 有趣的是,当我使用初始化代码时,我正在设置框架和图像。设置图像一切正常,但我设置的框架无关紧要,它始终是默认大小和位置。
  • 你的帖子非常有用!
【解决方案2】:

我相信你不能在 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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多