iOS 横竖屏

作者: 江河_ios | 来源:发表于2022-06-17 20:04 被阅读0次

    appdelegate.h实现

    @property(nonatomic, assign) BOOL allowLandscape; //允许横竖屏yes为横屏no为竖屏
    

    appdelegate.m实现

     -(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
     {
    if (self.allowLandscape == 1) {
        return UIInterfaceOrientationMaskAll;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
    }
    

    vc.m实现

     - (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //在视图出现的时候,将allowRotate改为1,
    AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    delegate.allowLandscape = 1;
    }
        - (void)viewWillDisappear:(BOOL)animated
    {
    [super viewWillDisappear:animated];
    //在视图出现的时候,将allowRotate改为0,
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowLandscape = 0;
    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 = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    }
     - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
     {
    // do something before rotation
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        //屏幕从竖屏变为横屏时执行
        
        NSLog(@"屏幕从竖屏变为横屏时执行");
    }else{
        //屏幕从横屏变为竖屏时执行
        NSLog(@"/屏幕从横屏变为竖屏时执行");
        
      }
    }
    

    按钮实现

    横屏

      [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
          self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
          self.view.bounds = CGRectMake(0, 0, KSCREEN_HEIGHT, KSCREEN_WIDTH);
    

    竖屏

     [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
          self.view.transform = CGAffineTransformMakeRotation(0);
          self.view.bounds = CGRectMake(0, 0, KSCREEN_WIDTH, KSCREEN_HEIGHT);
    

    相关文章

      网友评论

        本文标题:iOS 横竖屏

        本文链接:https://www.haomeiwen.com/subject/dyuhvrtx.html