开发者

How do I set the first UIViewController's view to autoresize?

I have a UIViewController subclass to handle my view for a landscape only application. I'd like for its view to resize to reflect the landscape dimensions automatically, but it doesn't seem to. A subview, however, does.

Here's the reproducing code.

@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

And then...

- (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;
}

Super simple. And yet, on boot, it logs:

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

The subview i开发者_高级运维s resized properly, but the parent view still has a portrait oriented frame.

How do I make the top level view resize to fit the landscape mode?


You have to allow the window autoresize subviews:

window.autoresizesSubviews=YES;


Use this in your viewController

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


self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

Add this in your viewdidload . Make sure in storyboard , Viewcontrollers view property is assigned to view


-(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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜