如何使子视图居中

时间:2013-05-04 11:12:36

标签: ios objective-c cocoa-touch

我将UIViewController子视图添加到另一个UIViewController。

效果很好。但是我很难尝试将子视图置于父视图的中间位置。

我读了,我找到了两行代码,但对我来说不起作用。

有人能指出我的问题吗?

那些是:

popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview];

popupController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);

父视图控制器代码:

- (IBAction)selectRoutine:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

    createRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"];
   // popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview];
    popupController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);

    //Tell the operating system the CreateRoutine view controller
    //is becoming a child:
    [self addChildViewController:popupController];

    //add the target frame to self's view:
    [self.view addSubview:popupController.view];

    //Tell the operating system the view controller has moved:
    [popupController didMoveToParentViewController:self];


}

enter image description here

儿童设置 enter image description here enter image description here

3 个答案:

答案 0 :(得分:2)

看起来像是在居中后重新定位视图控制器视图。可能在didMoveToParentViewController:

将居中代码移至selectRoutine:方法

的末尾
- (IBAction)selectRoutine:(id)sender
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

    createRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"];

    [self addChildViewController:popupController];
    [self.view addSubview:popupController.view];
    [popupController didMoveToParentViewController:self];

    //do the centering here
    popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview];

}

或者更好的是,将其移至didMoveToParentViewController:

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    //whatever code you have here

    self.view.center = self.view.superview.center;
}

可能您需要稍微修改此代码。但我确定你的问题是不正确的(执行时间)放置中心代码 - 随后被其他一些视图定位覆盖。

答案 1 :(得分:1)

为了将子视图移动到视图中心,我尝试了这个

YourView.center = CGPointMake(self.view.center.x,self.view.center.y);

答案 2 :(得分:0)

此处发布的解决方案适合我。通常,如果您希望微调器介于UIAlertController消息(通常位于UIAlertController的中心)和下面的任何操作按钮(如Ok或取消)之间,请稍微调整它的高度

spinnerIndicator.center = CGPointMake(self.superview.view.bounds.width / 2,
            (self.alertVC.view.bounds.height / 2) * 1.07)
// The superview of the spinnerIndictator here is the UIAlertController. 

根据我的实验,比率1.07将微调器放在所有可用iPhone屏幕下方的消息和操作按钮之间。