6

ViewController からデバイスの向きを取得する必要があります。に基づくことはできません

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

ときどき方向不明を返すためです (たとえば、デバイスがテーブルに置かれている場合)。

現在の UIView がどの方向で表示されているかを知る必要があるだけです(左に横向きか右に横向きか)。向きが変わったときにこの値を更新する必要はありません。求めたときに知りたいだけです。参照view.orientation ;)。私を助ける何かがありますか?UIView のドキュメントを読み、UIWindow への参照を見つけましたが、何も役に立ちませんでした。

4

4 に答える 4

13

UIApplication からデバイスの向きを取得することもできます。

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
于 2012-04-26T12:31:29.477 に答える
5

UIViewControllerにはプロパティがあります

UIInterfaceOrientation interfaceOrientation;

したがって、UIViewControllerでは、デバイスの現在の向きにいつでもアクセスできます。

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation;
于 2013-03-05T17:49:38.700 に答える
0

スウィフト版

    let currentOrientation:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation


    if currentOrientation.isPortrait {

        print("PORTRAIT")

    } else if currentOrientation.isLandscape {

        print("LANDSCAPE")

    }
于 2016-06-01T01:14:04.603 に答える
-1

以下は、同じことを行うサンプルコードです。deviceOrientationという名前の変数があり、尋ねられるたびにデバイスの現在の向きに答えます。

UIDeviceOrientation deviceOrientation;

- (void)viewWillAppear:(BOOL)animated
{
    deviceOrientation = (UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
    [self willAnimateRotationToInterfaceOrientation:deviceOrientation duration:0.5];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
    deviceOrientation = (UIDeviceOrientation)interfaceOrientation;
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        NSLog(@"Landscape");
    }
    else
    {
        NSLog(@"Portrait");
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return TRUE;
}
于 2012-04-26T12:32:46.787 に答える