How to detect Orientation Change in Custom Keyboard Extension in iOS 8?
Non-deprecated and will work on any device screen size (including future screen sizes Apple will be releasing this year).
In CustomKeyboard ViewController.m
:
-(void)viewDidLayoutSubviews {
NSLog(@"%@", (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) ? @"Portrait" : @"Landscape");
}
done.
Or... for a more easy to read version of this code:
-(void)viewDidLayoutSubviews {
int appExtensionWidth = (int)round(self.view.frame.size.width);
int possibleScreenWidthValue1 = (int)round([[UIScreen mainScreen] bounds].size.width);
int possibleScreenWidthValue2 = (int)round([[UIScreen mainScreen] bounds].size.height);
int screenWidthValue;
if (possibleScreenWidthValue1 < possibleScreenWidthValue2) {
screenWidthValue = possibleScreenWidthValue1;
} else {
screenWidthValue = possibleScreenWidthValue2;
}
if (appExtensionWidth == screenWidthValue) {
NSLog(@"portrait");
} else {
NSLog(@"landscape");
}
}
In order to update your custom keyboard when the orientation changes, override viewDidLayoutSubviews
in the UIInputViewController
. As far as I can tell, when a rotation occurs this method is always called.
Additionally, as the traditional [UIApplication sharedApplication] statusBarOrientation]
doesn't work, to determine the current orientation use the following snippet:
if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
//Keyboard is in Portrait
}
else{
//Keyboard is in Landscape
}
Hopefully this helps!