1. 程式人生 > 實用技巧 >iOS 橫豎屏切換解決方案

iOS 橫豎屏切換解決方案

https://www.cnblogs.com/qqcc1388/p/7358552.html

iOS要實現橫豎屏切換很簡單,不需要使用任何第三方,只需要實現幾個方法就可以了。demo下載地址:https://github.com/qqcc1388/TYOrientationDemo

1.設定系統支援橫豎屏【General】->【Targets】-> 【Deployment info】->【Device Orientation】

2.在控制器中實現對應的方法(預設支援豎屏)

-(BOOL)shouldAutorotate{
    return YES;
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

3.某些特定的頁面需要橫屏支援的,則單獨處理(同樣需要實現2個方法)

-(BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight);
}

4.如果控制器中有用到導航控制器或者tabbarController,這需要在導航控制器和tabbarController分別實現以下2個方法

- (BOOL)shouldAutorotate{
    
    return [self.selectedViewController shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return [self.selectedViewController supportedInterfaceOrientations];
}

5.如果需要實現點選按鈕切換橫豎屏的效果則可以參考如下方案:

//按鈕點選事件
- (void)leftAction
{
    [self interfaceOrientation:UIInterfaceOrientationPortrait];
}

- (void)rightAction
{
    [self interfaceOrientation:UIInterfaceOrientationLandscapeRight];
}

- (void)interfaceOrientation:(UIInterfaceOrientation)orientation
{
    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                  = orientation;
        // 從2開始是因為0 1 兩個引數已經被selector和target佔用
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

6.如果要監聽螢幕旋轉事件則可以參考如下方案(監聽旋轉事件,控制鍵盤,控制frame等操作)

    UIDevice *device = [UIDevice currentDevice]; //Get the device object
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification  object:device];

-(void)orientationChanged:(NSNotification *)noti{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    switch (orientation) {
        case UIDeviceOrientationPortrait:            // Device oriented
            break;
        case UIDeviceOrientationPortraitUpsideDown:  // Device oriented
            break;
        case UIDeviceOrientationLandscapeLeft :      // Device oriented
            break;
        case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
            break;
        default:
            break;
    }
}