What is the best way to detect orientation in an app extension?

邮差的信 提交于 2019-11-28 09:13:44

I faced with that problem and looked through your examples too, but there wasn't a good solution of it. How I resolved it: I created a class that does some calculations of the UIScreen values and returns the self defined device orientation.

Class Header:

typedef NS_ENUM(NSInteger, InterfaceOrientationType) {
    InterfaceOrientationTypePortrait,
    InterfaceOrientationTypeLandscape
};

@interface InterfaceOrientation : NSObject

+ (InterfaceOrientationType)orientation;

@end

Implementation:

@implementation InterfaceOrientation

+ (InterfaceOrientationType)orientation{

    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize nativeSize = [UIScreen mainScreen].currentMode.size;
    CGSize sizeInPoints = [UIScreen mainScreen].bounds.size;

    InterfaceOrientationType result;

    if(scale * sizeInPoints.width == nativeSize.width){
        result = InterfaceOrientationTypePortrait;
    }else{
        result = InterfaceOrientationTypeLandscape;
    }

    return result;
}

@end

I put it to viewWillLayoutSubviews or viewDidLayoutSubviews methods to catch the orientation changes event.

if([InterfaceOrientation orientation] == InterfaceOrientationTypePortrait){
     // portrait   
}else{
     // landscape   
}

In case you want to get an exact side of the device orientation (left, right, upside down) this approach won't resolve your problem. It just returns either the portrait or landscape orientations.

Hope it will help you.

You can get the device orientation in extension by adding a observer on UIApplicationWillChangeStatusBarOrientationNotification and then extracting the orientation as follows.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
}

- (void)orientationWillChange:(NSNotification*)n
{
    UIInterfaceOrientation orientation = (UIInterfaceOrientation)[[n.userInfo objectForKey:UIApplicationStatusBarOrientationUserInfoKey] intValue];

    if (orientation == UIInterfaceOrientationLandscapeLeft)
        //handle accordingly
    else if (orientation == UIInterfaceOrientationLandscapeRight)
        //handle accordingly
    else if (orientation == UIInterfaceOrientationPortraitUpsideDown)
        //handle accordingly
    else if (orientation == UIInterfaceOrientationPortrait)
        //handle accordingly
}

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!