iPhone中的Webview会自动调整大小以适应纵向和横向视图

6

我刚接触 iPhone 开发。在我的应用中,我希望以垂直方向显示设备上的网页视图。它还应该支持横向方向。我使用了下面的方法,但没有达到预期的效果。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{

return (interfaceOrientation == UIInterfaceOrientationPortrait || 

 interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == 

UIInterfaceOrientationLandscapeRight);
}

请指导我。请帮帮我。谢谢。

2个回答

11

我认为你已经为Web视图设置了固定框架。这在实现方向更改时是没有帮助的。

尝试使用以下代码来显示web视图。将stack-overflow URL更改为您的URL:

contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.view = contentView;
self.view.autoresizesSubviews = YES;


CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
webFrame.origin.y -= 20.0;

webView = [[UIWebView alloc] initWithFrame:webFrame];

[contentView addSubview:webView]; 
webView.scalesPageToFit = YES;
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
[webView setBackgroundColor:[UIColor clearColor]];
NSString *urlAddress = @"https://www.stackoverflow.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
webView.delegate =self;
[webView release];
为了支持方向。
   - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) orientation 
{
return YES;

}

用于Web视图随方向更改

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if(fromInterfaceOrientation == UIInterfaceOrientationPortrait){
 [webView stringByEvaluatingJavaScriptFromString:@"rotate(0)"];

}
else{
    [webView stringByEvaluatingJavaScriptFromString:@"rotate(1)"];
}
}

希望以上内容能够满足您的需求。 祝一切顺利。


谢谢。我想在我的WebView中显示工具栏,我该怎么做呢?我无法在我的WebView中看到工具栏。 - Pugalmuni
@pugal 将选项卡栏作为子视图插入... [self.view insertSubview:tBar belowSubview:contentView]; 将tBar更改为您使用的工具栏。 - Warrior

0
如果您想支持任何方向,请返回YES
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) orientation 
{
    return YES;
}

这在iOS 6中已被弃用:https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#jumpTo_9 - poshaughnessy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接