简体   繁体   中英

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..

+(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.

[[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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