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

时间:2016-05-04 08:31:58

标签: ios objective-c xcode7 orientation landscape-portrait

+(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;
    }
    }
}

当我的设备按纵向方向按照上述方法返回纵向值但问题是纵向有时会返回纵向值,有时会返回横向值,但我的设备始终处于纵向。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

将此代码复制到viewdidload中。

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

并在您的课程中复制此方法

- (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!");

    }
  }

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

答案 2 :(得分:0)

为什么你没有使用

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

或者你可以使用这个

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

或者这个

{{1}}

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