问题描述
在应用程序扩展中检测设备方向的最佳方法是什么?我在这里找到的解决方案结果好坏参半:
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:
我查看了大小类和 UITraitCollection
,发现该设备实际上处于横向状态时报告显示它是纵向的(不确定这是否是操作系统错误,或者我没有以正确的方式查询正确的API)。
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:
- 首次加载分机时设备的当前方向
- 设备将旋转的方向
- 设备旋转的方向
谢谢,
推荐答案
我遇到了这个问题,看了看你的问题例子,但没有一个很好的解决方案。
我如何解决它:我创建了一个类,它对UIScreen值进行一些计算并返回自定义的设备方向。
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.
类标题:
typedef NS_ENUM(NSInteger, InterfaceOrientationType) {
InterfaceOrientationTypePortrait,
InterfaceOrientationTypeLandscape
};
@interface InterfaceOrientation : NSObject
+ (InterfaceOrientationType)orientation;
@end
实施:
@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
我把它放到viewWillLayoutSubviews或viewDidLayoutSubviews捕获方向更改事件的方法。
I put it to viewWillLayoutSubviews or viewDidLayoutSubviews methods to catch the orientation changes event.
if([InterfaceOrientation orientation] == InterfaceOrientationTypePortrait){
// portrait
}else{
// landscape
}
如果您想获得设备方向的确切一侧(左,右,上下),这种方法将无法解决您的问题。它只返回纵向或横向方向。
希望它能帮到你。
这篇关于在应用扩展程序中检测方向的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!