简体   繁体   English

设备方向在iOS中无法正常工作

[英]Device orientation not work properly in iOS

+(CGFloat)maxTextWidth
{
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
    {
        if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
           {
        return 220.0f;
           }
           else
           {
               return 400.0f;
           }
    }
    else
    {
        if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
        {
        return 400.0f;
        }
    else
    {
        return 700.0f;
    }
    }
}

when my device in portrait orientation according to the above method it return the portrait value but the problem is that in portrait orientation sometimes it return the portrait value and sometimes it return landscape value but my device always in portrait orientation. 当我的设备按照上述方法处于纵向时,它返回纵向值,但问题是在纵向时,有时它返回纵向值,有时返回横向值,但是我的设备始终处于纵向。

In your if statement check status bar orientation instead of device orientation.. 在if语句中,检查状态栏的方向,而不是设备的方向。

+(CGFloat)maxTextWidth
{
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
    {
        if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
           {
        return 220.0f;
           }
           else
           {
               return 400.0f;
           }
    }
    else
    {
        if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
        {
        return 400.0f;
        }
    else
    {
        return 700.0f;
    }
    }
}

Copy this code in your viewdidload. 将此代码复制到您的viewdidload中。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didrotatedevice:) name:UIDeviceOrientationDidChangeNotification object:nil];

and copy this method in your class 并在您的课堂上复制此方法

- (void)didrotatedevice:(NSNotification *)notification
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];


    if (orientation == UIDeviceOrientationLandscapeLeft)
    {
          NSLog(@"Landscape Left!");

    }
    else if (orientation == UIDeviceOrientationLandscapeRight)
    {
         NSLog(@"Landscape Right!");

    }
    else
    {
          NSLog(@"Potrait!");

    }
  }

Let me know if you have any doubts? 让我知道您是否有任何疑问?

Why you didn't use 为什么你不使用

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

Or you can use this 或者你可以用这个

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

Or this 或这个

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

These methods detect any orientation changes. 这些方法可检测任何方向变化。 Set your UI changes in these methods. 在这些方法中设置您的UI更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM