UIWindow не поворачивается при изменении ориентации устройства

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

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

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

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;
}

ВнешнийВК.м

- (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];
}];


}

person Monika Patel    schedule 20.09.2019    source источник
comment
здесь вы идете для вашего аналогичного сценария stackoverflow.com/questions/6697605/ проверьте решение @Mecki, которое он дал простой выход,   -  person Abu Ul Hassan    schedule 20.09.2019
comment
@AbuUlHassan Я пробовал все решения по этой ссылке. но не работал.   -  person Monika Patel    schedule 20.09.2019
comment
@AbuUlHassan Я использовал (github.com/rdhiggins/ExternalScreenDemo) эту демонстрацию. И использовал (airsquirrels.com/reflector) это программное обеспечение, оно работает как проектор. Нам просто нужно подключить наше приложение с помощью зеркалирования экрана. Если у вас есть время, пожалуйста, проверьте и дайте мне знать, если вы можете помочь в этом. Благодарность   -  person Monika Patel    schedule 20.09.2019
comment
извините, я отсутствовал, я не сталкивался с такой проблемой, поэтому, может быть, я понятия не имею, даже я мог бы проверить это, но у меня нет проектора;)   -  person Abu Ul Hassan    schedule 23.09.2019
comment
@AbuUlHassan Хорошо, без проблем. но если у вас просто нет проектора, то я сказал вам, что вы можете использовать (airsquirrels.com/ отражатель) это программное обеспечение. вам просто нужно загрузить это программное обеспечение, оно даст вам 7-дневный пробный период. поэтому, когда вы установите это, оно будет работать как проектор.   -  person Monika Patel    schedule 23.09.2019
comment
ладно позвольте мне попробовать   -  person Abu Ul Hassan    schedule 23.09.2019
comment
@AbuUlHassan спасибо .. Буду ждать твоего ответа.   -  person Monika Patel    schedule 23.09.2019
comment
Хорошо, как я могу подключить его к своему iPad? или как я могу использовать его с? мак?   -  person Abu Ul Hassan    schedule 23.09.2019
comment
вам просто нужно запустить это программное обеспечение отражателя, а затем включить зеркальное отображение экрана с вашего iPad.   -  person Monika Patel    schedule 23.09.2019
comment
хорошо, но github.com/rdhiggins/ExternalScreenDemo находится в Swift, а ваш код находится в Objective-C. твой код где-то?   -  person Abu Ul Hassan    schedule 23.09.2019
comment
Давайте продолжим это обсуждение в чате.   -  person Monika Patel    schedule 23.09.2019
comment
см. чат, пожалуйста.   -  person Abu Ul Hassan    schedule 23.09.2019
comment
drive.google.com/file/d/1JUrLD4UybaOuwjanFbl4MWzwDZKfjaUW/view   -  person Monika Patel    schedule 23.09.2019
comment
Итак, второе окно, которое является внешним окном, созданным на основе отображения внешнего экрана. В результате вы должны работать в текущем окне, вы можете добавить внешнее окно в качестве окна-заполнителя, выберите свое изображение, а затем скройте внешнее окно с внешнего экрана после завершения обработки изображения, вы можете добавьте это окно снова, чтобы внешний зритель не мог видеть ваше внутреннее приложение, что вы говорите?   -  person Abu Ul Hassan    schedule 25.09.2019


Ответы (1)


Вот вам и ваше вращающееся окно, теперь вам нужно также вращать изображение, когда окно вращается. Делайте другие изменения, как хотите, я дал вам повернутое окно с поворотом устройства, просто замените 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
person Abu Ul Hassan    schedule 25.09.2019