2012-03-06 87 views
5

所以我有一个UIWebView显示静态HTML内容。UIWebView - 不会在轮换更改时调整内容大小?

当我以纵向方式启动ViewController并切换到横向时,它会正确调整内容的大小。

但是,当我在横向中启动页面并切换到纵向时,它不会调整我的内容大小,并且需要滚动才能查看所有内容。

这是一个错误?有没有解决方案来强制调整UIWebView的内容?

+0

请参阅http:// stackoverflow。com/questions/6007904/uiwebview-donest-resize-correct-when-orientation-change – buley 2014-08-16 02:18:43

回答

8

你有2种选择:
此添加到您的HTML文件的HEAD部分:

<meta name="viewport" content="width=device-width" /> 

或致电[myWebView reload]当朝向改变

+0

我已经尝试了第一个选项,它仍然留下了大约5个我不喜欢的滚动像素。明天我会尝试第二种解决方案,如果这不会导致webView在重新加载时闪烁,这将是一个可接受的解决方案。谢谢 – aryaxt 2012-03-06 01:54:00

3

我也有类似的问题。我解决它通过执行JavaScript代码来生成更新页面的方向的情况下,当UIViewController完成旋转:

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation 
{ 
    [webView stringByEvaluatingJavaScriptFromString:@"var e = document.createEvent('Events'); " 
                @"e.initEvent('orientationchange', true, false);" 
                @"document.dispatchEvent(e); "]; 
} 
+0

没有为我工作 – aryaxt 2012-03-26 16:00:27

+0

甚至不适合我。 – Tarun 2012-07-31 09:30:58

1

这个问题是老了,但是这应该解决这个问题:

myWebView.scalesPageToFit = YES;

或者,如果您使用的是界面构建器,则可以在属性检查器中勾选“销售页面拟合”复选框。

希望它有帮助。

+0

谢谢先生!没有意识到解决方案是那么简单。 – 2016-04-07 23:00:35

+2

没有为我工作! – 2016-09-03 10:24:20

0

我结束了使用@Sergey Kuryanov的第二种方法,因为第一种方法不适合我。我使用的是UIWebView的loadHTMLString方法,因此您会在代码中看到,但您可以用您用来在UIWebView中加载数据的任何方法替换它。

要做的第一件事是订阅轮换通知。为了做到这一点,我遵循@ clearwater82在这个问题上的回答:How to detect rotation for a programatically generated UIView
我重写了他对Swift 3的回答,你可以在同一页面找到它。

一旦完成,使用loadHTMLString轻松重新加载UIWebView中的数据。我的方法是将UIWebView封装在自定义视图中,以便我可以直接在自定义视图中处理HTML的一些格式。这使添加“重新加载旋转”功能变得非常简单。下面是我使用的代码,更多的细节在链接的答案:

// Handle rotation 
UIDevice.current.beginGeneratingDeviceOrientationNotifications() 
NotificationCenter.default.addObserver(
    self, 
    selector: #selector(self.orientationChanged(notification:)), 
    name: NSNotification.Name.UIDeviceOrientationDidChange, 
    object: nil 
) 

// Called when device orientation changes 
func orientationChanged(notification: Notification) { 
    // handle rotation here 
    self.webView.loadHTMLString(self.htmlText, baseURL: nil) 
} 

deinit { 
    NotificationCenter.default.removeObserver(self) 
    UIDevice.current.endGeneratingDeviceOrientationNotifications() 
} 

我只是想指出两点:

  • self.htmlText是抱着HTML文本我要加载的变量I添加到我的自定义视图
  • 使用UIDevice.current.endGeneratingDeviceOrientationNotifications()是适合我的情况,这可能不是你的

这一切,欢呼声

相关问题