Как определить изменение ориентации в пользовательском расширении клавиатуры в iOS 8?
В пользовательском расширении клавиатуры мы не можем использовать
`didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation`
и sharedApplication
.
Мне нужно обнаружить портрет или пейзаж на клавиатуре при вращении.
Как я могу определить изменение ориентации в расширении Custom Keyboard?
Ответы
Ответ 1
Чтобы обновить пользовательскую клавиатуру при изменении ориентации, переопределите viewDidLayoutSubviews
в UIInputViewController
. Насколько я могу судить, когда происходит поворот, этот метод всегда вызывается.
Кроме того, поскольку традиционный [UIApplication sharedApplication] statusBarOrientation]
не работает, для определения текущей ориентации используйте следующий фрагмент:
if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
//Keyboard is in Portrait
}
else{
//Keyboard is in Landscape
}
Надеюсь, это поможет!
Ответ 2
Без устаревания и будет работать на любом экране экрана устройства (включая будущие размеры экрана Apple выпустит в этом году).
В 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");
}
сделано.
:
:
Или..................
Для более легкой для чтения версии этого кода:
-(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");
}
}
Ответ 3
Существует простой способ, просто глядя на ширину экрана:
double width = [[UIScreen mainScreen] bounds].size.width;
double interfaceWidth = MIN([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
BOOL isPortrait = (width == interfaceWidth) ? YES : NO;
Ответ 4
использовать viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:
внутри вашего viewController
Ответ 5
- (void)updateViewConstraints {
[super updateViewConstraints];
// Add custom view sizing constraints here
if (self.view.frame.size.width == 0 || self.view.frame.size.height == 0)
return;
[self.inputView removeConstraint:self.heightConstraint];
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat screenH = screenSize.height;
CGFloat screenW = screenSize.width;
BOOL isLandscape = !(self.view.frame.size.width ==
(screenW*(screenW<screenH))+(screenH*(screenW>screenH)));
NSLog(isLandscape ? @"Screen: Landscape" : @"Screen: Potriaint");
self.isLandscape = isLandscape;
if (isLandscape) {
self.heightConstraint.constant = self.landscapeHeight;
[self.inputView addConstraint:self.heightConstraint];
} else {
self.heightConstraint.constant = self.portraitHeight;
[self.inputView addConstraint:self.heightConstraint];
}
//trigger default first view
[btn_gif sendActionsForControlEvents: UIControlEventTouchUpInside];
}
Ответ 6
willRotateToInterfaceOrientation
и didRotateFromInterfaceOrientation
можно использовать, я просто попробовал это на своем iPad, используя клавиатуру на iOS 8.1. Обратите внимание, что они устарели в iOS 8, но их замена willTransitionToTraitCollection
не называется, хотя вероятно, потому что коллекция признаков не меняется для клавиатуры при вращении.
Ответ 7
Перед iOS 8.3 вы должны использовать
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
Это не работает (это должно быть ошибка):
-(void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
На iOS 8.3 и более поздних версиях лучше использовать
-(void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
потому что
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
устарел.
Ответ 8
В somecase [UIScreen mainscreen].боты могут не работать. Иногда он обновляется после viewWillTransitionToSize:
Попробуйте это
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat realScreenHeight = MAX(screenSize.height, screenSize.width);
if(size.width == realScreenHeight)
NSLog(@"Landscape");
else
NSLog(@"Portrait");
}
Ответ 9
- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
{ UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; // do whatever
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { }]; [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
}