第一步:
首先,我定義了一個(gè)變量isFullScreen,用于判斷當(dāng)前視圖是處于橫屏狀態(tài)還是豎屏狀態(tài)。YES為橫屏,NO為豎屏。
BOOL _isFullScreen
第二步:
我寫(xiě)了一個(gè)方法用于執(zhí)行轉(zhuǎn)屏的操作,不論是橫屏,還是豎屏操作都可以調(diào)用這個(gè)方法,里面會(huì)根據(jù)當(dāng)前的狀態(tài),判斷是該橫屏還是豎屏!
- (void)changeScreenAction{
SEL selector=NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = _isFullScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
解析:
- 找到setOrientation:方法對(duì)應(yīng)的SEL類型的數(shù)據(jù),我用了一個(gè)局部變量selector暫存起來(lái)
SEL selector=NSSelectorFromString(@"setOrientation:");
2.NSInvocation 是實(shí)現(xiàn)命令模式的一種,可以調(diào)取任意的SEL或block。當(dāng)NSInvocation被調(diào)用,它會(huì)在運(yùn)行時(shí),通過(guò)目標(biāo)對(duì)象去尋找對(duì)應(yīng)的方法,從而確保唯一性。
NSInvocation創(chuàng)建方法
+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)sig;
NSMethodSignature是一個(gè)方法簽名的類,通常使用下面的方法,獲取對(duì)應(yīng)方法的簽名
[消息接受者 instanceMethodSignatureForSelector:selector];
eg:
NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
3.設(shè)置方法:
[invocation setSelector:selector];
4.設(shè)置執(zhí)行方法的對(duì)象
[invocation setTarget:[UIDevice currentDevice]];
5.判斷當(dāng)前的狀態(tài)是橫屏還是豎屏。利用三目運(yùn)算符,得到UIInterfaceOrientationLandscapeRight(橫屏)或UIInterfaceOrientationPortrait(豎屏),得到的結(jié)果其實(shí)是一個(gè)枚舉,如下:
typedef NS_ENUM(NSInteger, UIInterfaceOrientation) {
UIInterfaceOrientationUnknown = UIDeviceOrientationUnknown,
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
}
對(duì)應(yīng)的代碼如下:
int val = _isFullScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
6.設(shè)置執(zhí)行方法的參數(shù)
- (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx;
argumentLocation傳遞的是參數(shù)的地址。index 從2開(kāi)始,因?yàn)? 和 1 分別為 target 和 selector。
7.調(diào)用這個(gè)方法
[invocation invoke];