将旋转事件捕获到 UIInputViewController

Catch rotation event into UIInputViewController

我正在开发自定义键盘,我正在尝试捕捉设备旋转事件。

我已经试过了:

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

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

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

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

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

但是没用。

iPad Air 2 模拟器 - iOS9

有什么想法吗?

并非所有视图控制器都会接收到过渡事件。我认为这取决于您的视图控制器是否位于 UINavigationController 或 UITabBarController 之类的容器控制器内,以及它们是否将更改传递给它们的子控制器。

接收方向更改的保证方法是注册 UIDevice 方向更改通知。有关通知事件的列表,请参阅 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/c/data/UIDeviceOrientationDidChangeNotification

以下是您在 ObjC 中的操作。应该很容易翻译成 Swift.

在您的应用程序中,委托使用以下方式激活方向更改:

 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

在你想要通知的视图控制器中添加方法来处理通知,添加和删除观察通知。

// Method to be called when orientation notification is changed.
- (void)orientationDidChange:(NSNotification *)notification { 
  // Add your code to deal with the orientation.
  // You can get the current orientation for UIDevice as follows:

  UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
}

// Adds observation of orientation change
-(void)addObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
     selector:@selector(orientationDidChange:) 
     name:@"UIDeviceOrientationDidChangeNotification" 
     object:nil];
}

// Removes observation of orientation change
-(void)removeObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

在适当的位置添加对 addObserverremoveObserver 的调用。例如 viewDidAppearviewDidDisappear

看起来这在我的 iOS 9 和 iPad Air 2 项目中有效:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
    print("hi")
}

看起来你试过了,但没用...

大多数与旋转相关的方法现已弃用。 Apple 正在转向尺寸和特征更改通知,而不是直接的设备方向更改通知。

此外,UIDevice.currentDevice().orientation 始终 returns 在具有完全访问权限和 beginGeneratingDeviceOrientationNotifications 的键盘扩展中未知。

正确的方法(以及文档中列为已弃用方法的替代方法)是

- viewWillTransitionToSize:withTransitionCoordinator:

很奇怪它对你不起作用。我刚刚在 iPad Air 2 iOS9 模拟器上的 UIInputViewController 中尝试了它并且它有效:

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)

您调试的目标是否正确?要从您的扩展程序中查看控制台消息,您必须将其设置为 运行 目标:

注意还有

- willTransitionToTraitCollection:withTransitionCoordinator:

但是这个不适用于 iPad,因为 iPad 总是常规的,横向和纵向都是常规的。