Симулятор iPad и внешний экран

#ios #ipad #ios-simulator #external-display

#iOS #iPad #ios-симулятор #внешний-дисплей

Вопрос:

у меня есть приложение, которое я хочу показать на внешнем экране.

Проблема в том, что когда я захожу Аппаратное обеспечение -> Внешние дисплеи и выбираю один из них — события не запускаются. Почему?

Это также не вводится:

 if ([[UIScreen screens] count] > 1)
 

Итак, я добавил следующий код:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     //SOME CODE ...
     [self checkForExistingScreenAndInitializeIfPresent];
     [self setUpScreenConnectionNotificationHandlers];
     return YES:
}

- (void)checkForExistingScreenAndInitializeIfPresent
{
if ([[UIScreen screens] count] > 1)
{
    // Get the screen object that represents the external display.
    UIScreen *secondScreen = [[UIScreen screens] objectAtIndex:1];
    // Get the screen's bounds so that you can create a window of the correct size.
    CGRect screenBounds = secondScreen.bounds;

    self.secondWindow = [[UIWindow alloc] initWithFrame:screenBounds];
    self.secondWindow.screen = secondScreen;

    self.externalWindow=[[ExternalDisplayViewController alloc]initWithNibName:@"ExternalDisplayViewController" bundle:nil];
    self.externalWindow.view.frame=screenBounds;

    self.secondWindow.rootViewController=self.externalWindow;
    // Set up initial content to display...
    // Show the window.
    self.secondWindow.hidden = NO;
    }
}

- (void)setUpScreenConnectionNotificationHandlers
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

[center addObserver:self selector:@selector(handleScreenDidConnectNotification:)
               name:UIScreenDidConnectNotification object:nil];
[center addObserver:self selector:@selector(handleScreenDidDisconnectNotification:)
               name:UIScreenDidDisconnectNotification object:nil];
}
 

ДОПОЛНЕНИЕ:

Просто попытался добавить код в viewDidLoad

Добавлено это:

 // Check for external screen.
if ([[UIScreen screens] count] > 1)
{

}
else {
}
 

Есть открытый внешний дисплей и симулятор — не входит в блок IF

Комментарии:

1. Я думаю, у вас должен быть этот код в контроллере представления, а не в делегате приложения. У меня похожий на ваш код, и он работает отлично.

2. Загруженный исходный код отсюда: mattgemmell.com/ipad-vga-output тоже не работает. Может быть, мне нужно что-то включить В симуляторе?

3. Я почти уверен, что у вас должен быть этот код в UIViewController подклассе. Контроллер представления «владеет» всеми представлениями, внутренними и внешними.

4. Я только что проверил свой старый код, который очень похож на тот, что у вас есть (просто содержится в контроллере представления), и он работает так, как ожидалось.

5. Эта строка кода [self checkForExistingScreenAndInitializeIfPresent]; должна присутствовать в обработчиках viewDidLoad: уведомлений и.

Ответ №1:

Проблема может быть связана с инициализацией ExternalDisplayViewController :

 self.externalWindow=[[ExternalDisplayViewController alloc]initWithNibName:@"ExternalDisplayViewController" bundle:nil];
 

Попробуйте это :

 [[ExternalDisplayViewController alloc]initWithNibName:@"ExternalDisplayViewController" bundle:nil];
 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self.externalWindow= = [storyboard instantiateViewControllerWithIdentifier:@"ExternalDisplayView"];
 

кроме того, вам необходимо переопределить это handleScreenDidConnectNotification

 -(void)handleScreenDidConnectNotification : (NSNotification *)aNotification{
    UIScreen *newScreen = [aNotification object];
    CGRect screenBounds = newScreen.bounds;
    self.alertForNotifyDisplay =  [[UIAlertView alloc] initWithTitle:@"External Display Connected." message:Nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [self.alertForNotifyDisplay show];

    if (!self.extWindow) {
        self.extWindow  = [[UIWindow alloc] initWithFrame:screenBounds];
        self.extWindow.screen = newScreen;

        [self checkForExistingScreenAndInitializeIfPresent];
    }

}
 

Комментарии:

1. Вы этого не поняли — проблема в том, что он не входит в блок IF — не обнаруживает имитируемый внешний дисплей

2. Проверьте отредактированный. Вам нужно обработать соединение и позвонить checkForExistingScreenAndInitializeIfPresent

3. У меня есть письменные обработчики, просто я не вставлял их сюда. Проблема в том, что этот код не вводит их, если я отключаю или включаю внешний дисплей

4. Загруженный исходный код отсюда: mattgemmell.com/ipad-vga-output тоже не работает. Может быть, мне нужно что-то включить В симуляторе?

5. С симулятором нет ничего общего, кроме включения. Далее все, что вам нужно сделать с кодом.

Ответ №2:

Вот мой полный код в моем UIViewController подклассе. Я проверил это с помощью симулятора 7.1, и он работает для меня (я запускаю приложение, а затем инициализирую внешний дисплей, как только он уже запущен):

 - (void)viewDidLoad {
    // Other viewDidLoad code…
    // Check and initialize big screen
    [self checkForExistingScreenAndInitializeIfPresent]; 
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // Register for second screen notifications
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(handleScreenDidConnectNotification:)
               name:UIScreenDidConnectNotification object:nil];
    [center addObserver:self selector:@selector(handleScreenDidDisconnectNotification:)
               name:UIScreenDidDisconnectNotification object:nil];
}

- (void)handleScreenDidConnectNotification:(NSNotification *)notification {
    [self checkForExistingScreenAndInitializeIfPresent];
}

- (void)handleScreenDidDisconnectNotification:(NSNotification *)notification {
    [self checkForExistingScreenAndInitializeIfPresent];
}

- (void)checkForExistingScreenAndInitializeIfPresent {
    if ([[UIScreen screens] count] > 1) {
        // Get the screen object that represents the external display.
        UIScreen *secondScreen = [[UIScreen screens] objectAtIndex:1];
        secondScreen.currentMode = secondScreen.preferredMode;
        secondScreen.overscanCompensation = 3;
        // Get the screen's bounds so that you can create a window of the correct size.
        CGRect screenBounds = CGRectMake(secondScreen.bounds.origin.x,
                                         secondScreen.bounds.origin.y,
                                         secondScreen.currentMode.size.width,
                                         secondScreen.currentMode.size.height);

        UIWindow *secondWindow = [[UIWindow alloc] initWithFrame:screenBounds];
        secondWindow.screen = secondScreen;
        // Setup external VC
        [ExternalScreenViewController sharedExternalScreen].window = secondWindow;
        // Set VC for second window
        secondWindow.rootViewController = [ExternalScreenViewController sharedExternalScreen];
        // Show the window.
        secondWindow.hidden = NO;
    } else {
        // What to do if disconnected
    }
} 
 

Он должен работать с незначительными изменениями.

Ответ №3:

Проблема была в бета-версиях OS и Xcode. Понижен до Maverics — и все работает как шарм

Ответ №4:

Это сводило меня с ума. Я использую версию 10.0 (10A255), и она не работала. Причина в том, что я смотрел на application:didFinishLaunchingWithOptions: для UIScreen.screens.count> 1

Это всегда будет 1

Вместо этого попробуйте следующее

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   let center = NotificationCenter.default
   center.addObserver(self, selector: #selector(didConnect(notification:)), name: UIScreen.didConnectNotification, object: nil)
   return true
}

@objc func didConnect(notification: Notification) {
    if UIScreen.screens.count > 1 {
        if let screen = UIScreen.screens.last {
            let window = UIWindow(frame: screen.bounds)
            window.screen = screen

            let vc = UIViewController(nibName: nil, bundle: nil)
            vc.view.backgroundColor = .red

            window.isHidden = false
            window.rootViewController = vc
            self.secondWindow = window // Will not show unless window variable is retained.
        }
    }
}