简体   繁体   中英

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. 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.

Does anyone know how to detect rotation in UIInputViewController ?

You're correct - those methods are not called in the UIInputViewController subclass for Keyboard Extensions (not sure about other extension types).

You need to override 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:

- (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.

It looks like Apple didn't provide this API method to the UIInputViewController.

You can infer the device orientation if the device width is greater than device height in viewWillAppear

Swift 4.2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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