以编程方式在iPhone中自动调整子视图

时间:2010-05-20 12:20:17

标签: iphone screen-orientation

我创建了一个UIViewController和一个带有两个UIButton的UIView。

self.view = [[UIView alloc]initWithFrame:CGRectMake( 0,0,320,480)];
self.view.autoresizesSubviews = YES;

self.view.backgroundColor = [UIColor redColor];
UIView *view;
view = [[UIVew alloc]initWithFrame:CGRectMake(0,0,320,480)];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
UIButton *button1;
button.frame = CGRectMake(100,130,120,50);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
[controller addSubview:view];

// […]

- (void)buttonAction:(id)sender
{
    // I have created another view for a purpose
    [view removeFromSuperview];
    UIView *view_obj;
    view_obj.backgroundColor = [UIColor greenColor];
    view_obj.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:view_obj];  
}

问题: 当我将方向更改为横向时,具有按钮的视图会调整大小,但是当我单击按钮时,将显示带有blueColor的视图而不会自动调整大小。 我可以在redColor中看到一半作为根视图,在greenColor中看到一半作为子视图。我也覆盖了ShouldAutoRotate方法并以编程方式完成了这个项目。 请回复我。

2 个答案:

答案 0 :(得分:0)

在Interface Builder中,选择视图对象,然后在检查器窗口的“查看属性”窗格中确保选择了状态栏和“导航栏”的“顶栏”(假设您的应用程序有导航栏) 。您将在“模拟用户界面元素”部分中看到这些位于顶部附近。这可以在确定UIViewController视图的大小时通知应用程序始终为这些留出空间。

答案 1 :(得分:-1)

尝试研究this问题。

或者

请参阅以下代码来自this question

- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation: (UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration {    
    UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;
    if (interfaceOrientation == UIInterfaceOrientationPortrait 
        || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        button1.frame = CGRectMake(100, 33, 226, 275);
        button2.frame = CGRectMake(440, 33, 226, 275);
        button3.frame = CGRectMake(100, 360, 226, 275);
        button4.frame = CGRectMake(440, 360, 226, 275);
        button5.frame = CGRectMake(100, 693, 226, 275);
        button6.frame = CGRectMake(440, 693, 226, 275);
    }
    else 
    {
        button1.frame = CGRectMake(100, 50, 226, 275);
        button2.frame = CGRectMake(400, 50, 226, 275);
        button3.frame = CGRectMake(700, 50, 226, 275);
        button4.frame = CGRectMake(100, 400, 226, 275);
        button5.frame = CGRectMake(400, 400, 226, 275);
        button6.frame = CGRectMake(700, 400, 226, 275);
    }
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation || UIInterfaceOrientationPortraitUpsideDown);
}