UIWindow не вращается при изменении ориентации устройства - PullRequest
0 голосов
/ 20 сентября 2019

Мой проект обладает функциональностью, я подключил свое приложение к внешнему дисплею, например, к проектору.Мое приложение работает в обоих направлениях.В моем приложении 2 окна.window1 - наше окно по умолчанию.Я создал window2, его имя - внешнее окно.Я создал внешнее окно, потому что я не хочу показывать все свое приложение на проекторе, поэтому я просто добавил контроллер представления в окне 2, а затем отобразил окно 2 на внешнем дисплее (проекторе).

Теперь проблема в том, что, когдаЯ изменяю ориентацию моего приложения, оно работает нормально, но window2 не вращается.Window2 всегда отображается в ландшафтном режиме.Я просто хочу установить ориентацию window2 так же, как window1.Я много пробовал, но не смог найти решение.

Пожалуйста, проверьте мой код.Я добавил код, как подключить приложение с внешним дисплеем.пожалуйста, проверьте и помогите мне, если я сделал что-то не так.

AppDelegate.m

 -(void)initExternalWindow
    {
        //Setup external screen window
        (AppObj).externalWindow = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        (AppObj).externalScreen = [sb instantiateViewControllerWithIdentifier:@"ExternalVC"];
        UINavigationController *navController=[[UINavigationController alloc] initWithRootViewController:(AppObj).externalScreen];

        navController.navigationBarHidden=YES;
        (AppObj).externalWindow.opaque = NO;

        (AppObj).externalWindow.rootViewController = navController;

        (AppObj).externalWindow.backgroundColor = view_bg_color;
        (AppObj).externalWindow.hidden = NO;
        (AppObj).externalWindow.opaque = NO;
        [(AppObj).externalWindow makeKeyAndVisible];
    }

ViewController.m

- (void)viewDidLoad {
     [self setupScreenConnectionNotificationHandlers];
 }
#pragma mark- External dispaly detections (Add Notifications)
- (void)setupScreenConnectionNotificationHandlers
{
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];

    [center addObserver:self selector:@selector(handleScreenConnectNotification:)
                   name:UIScreenDidConnectNotification object:nil];
    [center addObserver:self selector:@selector(handleScreenDisconnectNotification:)
                   name:UIScreenDidDisconnectNotification object:nil];
}
- (void)handleScreenConnectNotification:(NSNotification*)aNotification
{
    [self setupExternalScreen];
}

- (void)handleScreenDisconnectNotification:(NSNotification*)aNotification
{
    if ((AppObj).externalWindow)
    {
        (AppObj).externalWindow.hidden = YES;
        (AppObj).externalWindow = nil;

    }
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

ExternalVC.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.updatedImg.image = (AppObj).updatedImg;
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
     {
//         UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
     } completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
     {
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
         [[UIDevice currentDevice] setValue:@(orientation) forKey:@"orientation"];


         [UINavigationController attemptRotationToDeviceOrientation];
         [UIViewController attemptRotationToDeviceOrientation];
}];


}

1 Ответ

0 голосов
/ 25 сентября 2019

Теперь вы работаете с окном поворота, теперь вы также должны повернуть изображение при повороте окна. Сделайте другие изменения, как вы хотите. Я дал повернутое окно с поворотом устройства, просто замените ExternalVC.m следующим кодом

    //
//  ExternalVC.m
//  Sketch
//
//  Created by mac on 21/07/18.
//  Copyright © 2018 mac. All rights reserved.
//

#import "ExternalVC.h"

@interface ExternalVC ()

@end

@implementation ExternalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.updatedImg.image = (AppObj).updatedImg;
    NSLog(@"External window bounds:%lu",(unsigned long)self.supportedInterfaceOrientations);
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(orientationDidChange:)
                   name:UIDeviceOrientationDidChangeNotification object:nil];

}

- (void)orientationDidChange:(NSNotification*)aNotification
{
      NSLog(@"orientation did change :%@",aNotification);
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
   // [self transformForOrientation:orientation];
    [self.view.window setTransform:[self transformForOrientation:orientation]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    if ([UIScreen mainScreen] == (AppObj).externalWindow.screen || !(AppObj).externalWindow) {
        return UIInterfaceOrientationMaskAll;
    }else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
     {
//         UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
     } completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
     {
//
//         NSLog(@"External window bounds:%f || %f",(AppObj).externalWindow.bounds.size.width,(AppObj).externalWindow.bounds.size.height);
//    //     UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
//     //    [(AppObj).externalWindow setValue:@(orientation) forKey:@"orientation"];
////         [[UIDevice currentDevice] setValue:@(orientation) forKey:@"orientation"];
////
////
////         [UINavigationController attemptRotationToDeviceOrientation];
//         [UIViewController attemptRotationToDeviceOrientation];
//          UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
//        [self transformForOrientation:orientation];

     }];


}

#define DegreesToRadians(degrees) (degrees * M_PI / 180)

- (CGAffineTransform)transformForOrientation:(UIDeviceOrientation)orientation {


//        [self.view.window setFrame:CGRectMake(0, self.view.window.frame.size.height-50, self.view.window.frame.size.width, [UIScreen mainScreen].bounds.size.height)];
//        [self.view.window makeKeyAndVisible];


    switch (orientation) {

        case UIInterfaceOrientationLandscapeLeft:
            NSLog(@"UIInterfaceOrientationLandscapeLeft****");
            return CGAffineTransformMakeRotation(DegreesToRadians(90));


        case UIInterfaceOrientationLandscapeRight:
            NSLog(@"UIInterfaceOrientationLandscapeRightt****");
            return CGAffineTransformMakeRotation(-DegreesToRadians(90));

        case UIInterfaceOrientationPortraitUpsideDown:
            NSLog(@"UIInterfaceOrientationUpSideDownPortrait****");
            return CGAffineTransformMakeRotation(DegreesToRadians(180));

        case UIInterfaceOrientationPortrait:
        default:
            NSLog(@"UIInterfaceOrientationPortait****");
            return CGAffineTransformMakeRotation(DegreesToRadians(0));
    }
}

- (void)statusBarDidChangeFrame:(NSNotification *)notification {

    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    NSLog(@"status bar orientation :%ld",(long)orientation);
  //  [self.view setTransform:[self transformForOrientation:orientation]];

}
-(BOOL)shouldAutorotate{
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
...