1.一般常用的方法
1)添加監(jiān)聽
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
2)判斷方向,強(qiáng)制橫豎屏
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = self.currentOrientation;
// 從2開始是因?yàn)? 1 兩個(gè)參數(shù)已經(jīng)被selector和target占用
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
2.由于上面監(jiān)聽的方法還會有其他的狀態(tài)UIDeviceOrientationUnknown/UIDeviceOrientationFaceUp導(dǎo)致一些復(fù)雜的業(yè)務(wù)處理的不是很好,無法精準(zhǔn)的判斷是橫屏還是豎屏,為此自己使用的方法是通過監(jiān)聽屏幕方向變化計(jì)算屏幕的寬高來精準(zhǔn)的判斷橫豎屏.
if ([KKUIDeviceOrientation defaultDeviceOrientation].deviceDirection == HorizonDirection) {
//橫屏
}else{
//豎屏
}
代碼如下:
#importtypedef enum : NSUInteger {
/**
*? 豎屏
*/
VerticalDirection,
/**
*? 橫屏
*/
HorizonDirection
} DeviceDirection;
@interface KKUIDeviceOrientation : NSObject
/**
*? 注意:先在要需要使用的地方調(diào)用一下(最好在appdelegate里初始化一下)
*/
+(instancetype)defaultDeviceOrientation;
/**
*? 屏幕方向
*/
@property(nonatomic,assign)DeviceDirection deviceDirection;
@end
#import "KKUIDeviceOrientation.h"
@interface KKUIDeviceOrientation ()
@end
@implementation KKUIDeviceOrientation
+(instancetype)defaultDeviceOrientation{
static KKUIDeviceOrientation* _instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[KKUIDeviceOrientation alloc] init];
_instance.deviceDirection = VerticalDirection;//默認(rèn)是豎屏
[_instance listenNotification];
});
return _instance;
}
-(void)listenNotification{
//屏幕橫豎屏切換的系統(tǒng)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)listenOrientationDidChange{
// 320(iphone5) 375(iphone6) 414(iphoneXplus)
CGFloat width = [UIScreen mainScreen].bounds.size.width;
if (width==320||width==375||width==414) {
self.deviceDirection = VerticalDirection;
}else{
self.deviceDirection = HorizonDirection;
}
}
iOS小白一枚,如有不對的地方,還望大神指正