在代码中设置视图,该视图随方向而变化

时间:2010-01-31 12:47:22

标签: iphone uiviewcontroller view rotation

我已经设置了一个应用程序并使用了“iPhone Developer's Cookbook”中的一些基本代码来创建一个简单的视图。应用程序在纵向模式下正常工作,但在旋转时,框的尺寸保持不变。这是我的代码:

- (void)loadView {
    //Create the full application frame (minus the status bar) - 768, 1004
    CGRect fullRect = [[UIScreen mainScreen] applicationFrame]; 

    //Create the frame of the view ie fullRect-(tabBar(49)+navBar(44)) - 768, 911
    CGRect viewRect = CGRectMake(0, 64, fullRect.size.width, fullRect.size.height-93.0);

    //create the content view to the size
    contentView = [[UIView alloc] initWithFrame:viewRect]; 
    contentView.backgroundColor = [UIColor whiteColor];

    // Provide support for autorotation and resizing 
    contentView.autoresizesSubviews = YES;
    contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    self.view = contentView; 
    [contentView release];

    // reset the origin point for subviews. The new origin is 0,0 
    viewRect.origin = CGPointMake(0.0f, 0.0f);

    // Add the subviews, each stepped by 32 pixels on each side 
    UIView *subview = [[UIView alloc] initWithFrame:CGRectInset(viewRect, 32.0f, 32.0f)]; 
    subview.backgroundColor = [UIColor lightGrayColor]; 
    [contentView addSubview:subview]; 
    [subview release];

    subview = [[UIView alloc] initWithFrame:CGRectInset(viewRect, 64.0f, 64.0f)]; 
    subview.backgroundColor = [UIColor darkGrayColor]; 
    [contentView addSubview:subview]; 
    [subview release];

    subview = [[UIView alloc] initWithFrame:CGRectInset(viewRect, 96.0f, 96.0f)]; 
    subview.backgroundColor = [UIColor blackColor]; 
    [contentView addSubview:subview]; 
    [subview release];
}

旋转时是否有任何方法可以重新加载新尺寸或更好地适应方向变化?

由于 JP

2 个答案:

答案 0 :(得分:1)

我可能误解了你的问题。用“方框”,你的意思是子视图吗?

如果是这样,子视图在旋转时将保持其外观尺寸,因为它们是正方形。

在任何情况下,viewDidLoad仅在首次初始化视图时调用,通常来自笔尖。如果您需要在视图轮换时对其进行更改,则需要在willRotateToInterfaceOrientation:duration:和/或didRotateFromInterfaceOrientation:中进行更改。

要更改任何视图的尺寸,只需重置其框架即可。

答案 1 :(得分:1)

object.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;