Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

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

What is the best way to detect a device's orientation in an application extension? I have had mixed results with solutions I've found on here:

How to detect Orientation Change in Custom Keyboard Extension in iOS 8?

Get device current orientation (App Extension)

I have looked at size classes and UITraitCollection and found that the device inaccurately reports that it is in portrait when it is in fact in landscape (not sure if this is OS bug, or I am not querying the right APIs the right way).

What is the best method for accomplishing:

  • The device's current orientation when the extension is first loaded
  • The orientation the device will rotate to
  • The orientation the device did rotate to

Thank you,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...