设备方向在 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;
    }
    }
}

当我的设备根据上述方法处于纵向时它 return 纵向值但问题是在纵向时有时它 return 纵向值有时它 return 横向值,但我的设备始终处于纵向。

为什么你没有使用

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

或者你可以使用这个

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

或者这个

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

这些方法检测任何方向变化。 在这些方法中设置您的 UI 更改。

在您的 viewdidload 中复制此代码。

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

并将此方法复制到您的 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!");

    }
  }

如果您有任何疑问,请告诉我?

在您的 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;
    }
    }
}