简体   繁体   中英

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.

I will be using a UIPageControl to swipe that view off to the left and bring in the new one from the right. I have added the UIImageView which normally just adds it to the bottom right corner

-(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. How do I position it correctly?

Move your code to viewDidAppear. Bounds and frames are not guaranteed to have been set till 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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM