Search code examples
iosswiftios9custom-keyboarduiinputviewcontroller

Catch rotation event into UIInputViewController


I'm developing a custom Keyboard and I'm trying to catch a device rotation event.

I've already tried :

override func viewDidLayoutSubviews() {
    print("Foo")
}

and

override func viewWillLayoutSubviews() {
    print("🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳 Bar")
}

and

override func didRotateFromInterfaceOrientation(sender : UIInterfaceOrientation){ 
    print("🐳🐳🐳🐳");
}

and

 override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    print("Bar")
}

and

override func updateViewConstraints() {
    super.updateViewConstraints()
    print("🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳 Foo")
}

But it's not working.

iPad Air 2 Simulator - iOS9

Any idea ?


Solution

  • Most of the methods related to rotation are deprecated now. Apple is moving towards sizes and traits changes notifications, and not so much direct device orientation change notifications.

    Also, UIDevice.currentDevice().orientation always returns Unknown in keyboard extensions with both Full Access and beginGeneratingDeviceOrientationNotifications.

    The correct method (and the one listed as replacement for the deprecated methods in the documentation) is

    - viewWillTransitionToSize:withTransitionCoordinator:
    

    It's strange that it didn't work for you. I just tried it in an UIInputViewController on iPad Air 2 iOS9 Simulator and it works:

    2015-10-13 12:28:15.347 [Info] [KeyboardViewController.swift:60] viewWillTransitionToSize(:withTransitionCoordinator:) > Rotate to size (1024.0, 313.0) 2015-10-13 12:28:20.512 [Info] [KeyboardViewController.swift:60] viewWillTransitionToSize(:withTransitionCoordinator:) > Rotate to size (768.0, 313.0)

    Are you debugging the correct target? To see console messages from your extension, you must set it as the run target: enter image description here

    Note that there is also

    - willTransitionToTraitCollection:withTransitionCoordinator:
    

    But this one won't work for the iPad, because the iPad is always Regular,Regular for both landscape and portrait.