iPhone UIWebView local resources using Javascript and handling onorientationChange

前端 未结 5 590
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 21:20

I\'m trying to server HTML Javascript and CSS content from an iPhone application\'s local resources, and I\'m having trouble handling onOrientationChange events and includin

5条回答
  •  春和景丽
    2020-11-28 21:56

    I've found iOS 4.2 does not support window.orientation property in UIWebView, while in mobile safari it works... So, the only way I have found in order to make my JS react to orientation changes was to make my objective-c code call a javascript function defined in currently displayed UIWebView webpage. Here's a sample code, overriding ViewController's didRotateFromInterfaceOrientation method:

    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        [webView stringByEvaluatingJavaScriptFromString:
              [NSString stringWithFormat:@"didRotateTo('%@')", 
                [self currentOrientationAsString]]];
    }
    - (NSString*) currentOrientationAsString {
        switch([[UIDevice currentDevice] orientation]) {
            case UIDeviceOrientationLandscapeLeft:
            case UIDeviceOrientationLandscapeRight:
                return @"landscape";
        }
        return @"portrait"; // assuming portrait is default
    }
    

    You have to define your Javascript function as follows:

    function didRotateTo(ori) {
      if (ori=="portrait") {
        // ... do something
      } else {
        // ... do something else
      }
    }
    

    Enjoy! :)

提交回复
热议问题