---
title: "UIWebView如何触发其中的Web页面的Orientation事件？"
author: "iame"
date: "2010-09-15T22:45:05Z"
tags: []
categories: ["移动开发"]
slug: "uiwebview-web-orientation"
draft: false
lastmod: "2010-09-15T22:45:05Z"
id: 764325
url: "https://iame.iteye.com/blog/764325"
---

最近在用sencha touch在iOS上试着开发一些native-like应用，遇到不少问题，其中之一就是通过UIWebView加载web页面时，如果转动屏幕，里面的Web页面不会自动适配高宽，但是用Safari浏览时却是可以的。

 

用Safari的Web检查器查看sencha touch生成的页面，发现sencha touch控件生成的HTML元素，都是指定了width/height的，当转动屏幕时，如果只是UIWebView转动，而不重新计算这些HTML元素的width/height，就会导致上述问题。

 

google了一下，[这篇文章](http://peerpong.com/q/bj94b-what-are-some-reasons-for-a-uiwebviews-html-document-not-knowing-when-the-device-is-rotated) 中说Safari中之所以可以自动适配sencha touch产生的HTML元素，是由于Safari在转动屏幕时，会触发document的orientationchange事件，从而sencha touch可以捕获这个事件，重新计算控件产生的HTML元素的高宽，达到自动适配的目的。而UIWebView的orientation是你自己的程序处理的，你也要在获取orientation事件时告诉web的document，方法就是通UIWebView.stringByEvaluatingJavaScriptFromString。但具体如何触发呢？

 

就是给document产生一个orientationchange事件，剩下的由sencha touch处理好了(sencha touch的所有控件都可以响应这个事件重新计算高宽)。

 

示例代码：

```
//add by iame
var e = document.createEvent('Events');
e.initEvent('orientationchange', true, false); 
document.dispatchEvent(e);
```

 

不需要设置具体是landscape,portrait，只需要设置事件名称对就好了。sencha touch会在处理事件时，自动判断是landscape,还是portrait。