繁体   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;
    }
    }
}

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

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

将此代码复制到您的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!");

    }
  }

让我知道您是否有任何疑问?

为什么你不使用

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

或者你可以用这个

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

或这个

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

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

暂无
暂无

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

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