简体   繁体   English

如何在超视图中定位UIView?

[英]How do I position UIView in superview?

Im adding a UIImageView with a UIImage which I wish to appear in the center top of the main UIView. 我添加了一个带有UIImage的UIImageView,我希望它出现在主UIView的中心顶部。

I will be using a UIPageControl to swipe that view off to the left and bring in the new one from the right. 我将使用UIPageControl将该视图向左滑动并从右侧引入新视图。 I have added the UIImageView which normally just adds it to the bottom right corner 我添加了UIImageView,通常只是将它添加到右下角

-(void)createUIViews{
    UIImage *image1 = [UIImage imageNamed:@"GiftCard.png"];
    firstView = [[UIImageView alloc] initWithImage:image1];
    firstView.backgroundColor = [UIColor grayColor];
    firstView.tag = 1;
    firstView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
}

Now I wish to position it at top center. 现在我希望将它定位在顶部中心。 So Im thinking of something like this: 所以我想到这样的事情:

CGRect newFrame = self.view.frame;
    newFrame.origin.x += 50;
    self.view.frame = newFrame;

    [self.view addSubview:firstView];

But when I add this code at the bottom of the previous one, (which btw is being called from viewDidLoad), the image still appears at the bottom right. 但是当我在前一个底部添加此代码时(从viewDidLoad调用btw),图像仍然显示在右下角。 How do I position it correctly? 我该如何正确定位?

Move your code to viewDidAppear. 将代码移动到viewDidAppear。 Bounds and frames are not guaranteed to have been set till viewWillAppear/viewDidAppear. 在viewWillAppear / viewDidAppear之前,不保证设置边界和框架。

Make sure you set your struts and springs appropriately and then just do this: 确保正确设置支柱和弹簧,然后执行以下操作:

 -(void)viewWillAppear:(BOOL)animated 
  {
    [super viewWillAppear:animated];
    firstView.center = self.center;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UIView。 如何快速找到根 SuperView? - UIView. How Do I Find the Root SuperView Fast? 如何参考UIView的位置和大小来更新UIView的位置和大小? [迅速] - How can I update a UIView's position and size in reference to it's superview's position and size? [Swift] 如何仅使用情节提要使 UILabel 的 UIView 超级视图适合 UILabel 的固有高度? - How do I make the UIView superview of a UILabel fit the intrinsic height of the UILabel using the storyboard only? 如何确定哪个UIView超级视图导致子视图具有userInteractionEnabled = NO? - How do I determine which UIView superview is causing the subview to have userInteractionEnabled = NO? 如何确保UIView缩小到其超级视图的大小? - How do you ensure that a UIView shrinks down to the size of its superview? 获取 UIView 相对于其父视图的父视图的位置 - Get position of UIView in respect to its superview's superview 如何在iOS中确定UIImageView的超级视图 - How do I determine the superview of UIImageView in iOS 如何找到最父级的SuperView? - How do I find the most parent SuperView? 如何拖动UIView元素并更改位置? - How do I drag UIView elements and change position? 如何获得CAShapeLayer的超级视图位置? - How to get CAShapeLayer superview position?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM