简体   繁体   English

在UIInputViewController子类中检测旋转。 键盘扩展

[英]Detect rotation in UIInputViewController subclass. Keyboard extension

I have been developing custom keyboard extension and I need to update few constraints programatically after device rotates. 我一直在开发自定义键盘扩展,并且在设备旋转后需要以编程方式更新一些约束。 I have been trying to detect user interface rotation in my UIInputViewController subclass but without success. 我一直在尝试在UIInputViewController子类中检测用户界面旋转,但没有成功。 These methods are not called when device rotates: 设备旋转时不会调用以下方法:

-(void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>) coordinator { NSLog(@"Orientation changed"); }

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { NSLog(@"Orientation changed"); }

I've also tried to observe UIDeviceOrientationDidChangeNotification but it doesn't work either. 我也尝试观察UIDeviceOrientationDidChangeNotification但它也不起作用。

Does anyone know how to detect rotation in UIInputViewController ? 有人知道如何在UIInputViewController检测旋转吗?

You're correct - those methods are not called in the UIInputViewController subclass for Keyboard Extensions (not sure about other extension types). 您是正确的-键盘扩展的UIInputViewController子类中未调用这些方法(不确定其他扩展类型)。

You need to override viewDidLayoutSubviews . 您需要覆盖viewDidLayoutSubviews

For example, if you wanted to update the layout of a UICollectionView subview of your keyboard when the device rotates, you'd do something like this: 例如,如果您想在设备旋转时更新键盘的UICollectionView子视图的布局,则可以执行以下操作:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    [self.keyboard.collectionView performBatchUpdates:nil completion:nil];
}

In your case you can check the orientation of the device in viewDidLayoutSubviews, and then apply/modify constraints appropriately. 您可以在viewDidLayoutSubviews中检查设备的方向,然后适当地应用/修改约束。

It looks like Apple didn't provide this API method to the UIInputViewController. 看来Apple没有为UIInputViewController提供此API方法。

You can infer the device orientation if the device width is greater than device height in viewWillAppear 如果设备宽度大于viewWillAppear设备高度,则可以推断设备方向

Swift 4.2 斯威夫特4.2

  override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {        
       let screen = UIScreen.main.bounds
        if screen.width < screen.height {
            print("!!! portrait")
        } else {
            print("!!! landspace")
        }
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM