旋转时确保视图保持全屏

时间:2011-12-06 14:04:28

标签: iphone objective-c ios ipad orientation

我在UIWebView方法中添加了UIViewController的简单viewDidLoad

CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
self.webView = [[UIWebView alloc] initWithFrame:rect];
self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.webView];

它看起来很棒,但是当我旋转手机时,宽度和高度保持不变,所以现在它对于更新视图框来说太宽了。我也尝试过使用self.view.bounds,但它没有任何区别。

那么如何确保加载时全屏视图在旋转时保持相同的大小? (不使用IB)

2 个答案:

答案 0 :(得分:0)

你在做什么是正确的&应该适用于大多数情况。但是因为我不知道你的View Stack。我会建议一个确定的射击方式 -

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                         duration:(NSTimeInterval)duration
{
    CGRect rect;
    if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft||toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
       rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
    else
    {
        //some other dimensions.
    }
     self.webView = [[UIWebView alloc] initWithFrame:rect];
}

答案 1 :(得分:0)

因为Web视图只调用一次,所以需要再次调用它 设置新框架

self.webView = [[UIWebView alloc] initWithFrame:rect];

所以你必须在viwewillappear或viewdidload

中注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewBecamePortrait:) name:@"orientationIsPortrait" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewBecameLandscape:) name:@"orientationIsLandscape" object:nil];



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
        NSNotification* notification = [NSNotification notificationWithName:@"orientationIsPortrait" object:self];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }else {
        NSNotification* notification = [NSNotification notificationWithName:@"orientationIsLandscape" object:self];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }
}

然后实施

-(void)viewBecameLandscape:(id)sender{
    if(webview){
      [webview.setframe(cgrectmake(x,y,width,height))];
    }
}
-(void)viewBecamePortrait:(id)sender{
}