reech
reech

Reputation: 340

Phonegap 2.2.0 - Detecting orientation

I have an app that I'd like to keep in portrait mode, except for a single view in which I want to detect an orientation change, fire a js event and change the orientation (for that view only).

I have the following code in my app:

   window.shouldRotateToOrientation = function(rotation) {
     switch (rotation) {        
       case 0:
       case 180:
        console.log("Portrait");
        return false;
        //LandscapeRight or LandscapeLeft
       case 90:
       case -90:
        console.log("Landscape");
        return false;
     }
  }

This seems to work okay when built for iOS5, keeping the app in Portrait orientation by returning false, and correctly firing when the device is in landscape mode. However when built for iOS6 the function is called 4 times each time the device the device is rotated, matching each case - rendering the detection useless.

Am I approaching this correctly - is there another way or is there something that I am missing?

Note that I have a very limited understanding of the XCode/ios/ObjectiveC environment

Upvotes: 4

Views: 6062

Answers (2)

bernalmurcia
bernalmurcia

Reputation: 64

The following works for me to detect the orientation:

function isOrientationPortrait(){
  if ($(window).height() > $(window).width()){ 
    return true; 
  } else { 
    return false; 
  }
}

$(window).on('orientationchange', function () {
  if(isOrientationPortrait()){
    console.log("Portrait");
  } else {
    console.log("Landscape"); 
  }
});

Upvotes: 0

Idan Gozlan
Idan Gozlan

Reputation: 3203

try this code:

function changeOrientation() {
    switch (window.orientation) {
        case 0:
            // portrait, home bottom
        case 180:
            // portrait, home top
            alert("portrait H: " + $(window).height() + " W: " + $(window).width());
            break;
        case -90:
            // landscape, home left
        case 90:
            // landscape, home right
            alert("landscape H: " + $(window).height() + " W: " + $(window).width());
            break;
    }
}

window.onorientationchange = function () {
    //Need at least 800 milliseconds
    setTimeout(changeOrientation, 1000);
}

The timeout should fix the problem.

Upvotes: 2

Related Questions