2011-08-02 15 views
3

我有一個UIViewController子類來處理我的景觀唯一的應用程序的視圖。我希望自己調整大小以自動反映景觀尺寸,但似乎並非如此。子視圖,但是,。如何將第一個UIViewController的視圖設置爲自動大小?

這是再現代碼。

@interface MyViewController : UIViewController { 
    UIView *subview; 
} 

@implementation MyViewController 

- (id)init 
{ 
    self = [super init]; 
    if (self) { 
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 

    subview = [[UIView alloc] initWithFrame:self.view.frame]; 
    subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    [self.view addSubview:subview]; 
    } 

    return self; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { 
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation); 
} 

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { 
    NSLog(@"My view's frame (%f,%f)", self.view.frame.size.width, self.view.frame.size.height); 
    NSLog(@"Subview's frame (%f,%f)", subview.frame.size.width, subview.frame.size.height); 
} 

@end 

然後......

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 
    self.window.rootViewController = [[MyViewController alloc] init]; 
    [self.window makeKeyAndVisible]; 
    return YES; 
} 

超級簡單。然而,在啓動時,它會記錄:

My view's frame (320.000000,480.000000) 
Subview's frame (480.000000,320.000000) 

子視圖的大小調整正確,但父視圖仍然有一個縱向框架。

如何使頂層視圖的大小適合橫向模式?

回答

0

試試這個:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 

    if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) { 

     //is portrait 

     view.frame = CGRectMake(0,0,320,480) 


    } else { 

     //is landscape 

     view.frame = CGRectMake(0,0,480,320); 

    } 
} 

希望這有助於!

+0

不幸的是,它只是硬編碼,這是微不足道的,但我想避免。即使在當前的設備生態系統中,代碼也需要另一個分支來檢查設備慣用語,手機或鍵盤。 –

2

使用此在您的viewController

self.view.frame = [[UIScreen mainScreen] bounds]; 
+0

如果使用此選項,則scrollview不起作用。 ?!?! – KennyVB

2

你必須允許窗口自動調整大小子視圖:

window.autoresizesSubviews=YES; 

希望這有助於!

+0

謝謝你。在不使用自動佈局時,選擇屬性檢查器下第一個視圖的autoresize子視圖。 –

1
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 

在viewDidLoad中添加此。確保在故事板中,Viewcontrollers視圖屬性被分配到視圖

相關問題