программная установка ориентации в viewdidload не работает
-
23-12-2019 - |
Вопрос
Я создал приложение для iPad, в котором домашний экран должен отображаться только в портретном режиме.Поэтому я использовал приведенный ниже код в viewdidload.
[[UIDevice currentDevice] setOrientation:UIDeviceOrientationPortrait];
Но это не работает.Я использую iOS 7 с Xcode 5.Если я открою свое приложение из ландшафтного режима, оно автоматически перейдет в портретный режим.но у меня получается вот так:
но должно быть так:
может ли кто-нибудь помочь мне решить эту проблему.Заранее спасибо.
Решение
[[UIDevice currentDevice] setOrientation:UIDeviceOrientationPortrait];
Этот метод устарел.Вы больше не можете использовать этот метод.
https://stackoverflow.com/a/12813644/1405008
Ссылка выше дает подробную информацию о том, как обеспечить только портретный режим для UIViewController
.
Если вы втолкнулись в NavigationViewController
тогда попробуй это.
Другие советы
Следующий код собирается преобразовать навигационно-образец вид из портрета в ландшафт программно:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.navigationController.view.transform = CGAffineTransformIdentity;
self.navigationController.view.transform = CGAffineTransformMakeRotation(M_PI*(90)/180.0);
self.navigationController.view.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
[UIView commitAnimations];
self.view.frame = self.view.frame; //This is necessary
self.wantsFullScreenLayout = YES;
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeRight;
}
.
Просто надеюсь предоставить вам другие идеи.
Скопируйте этот код в вашей ViewDidload
UIInterfaceOrientation orientation = (UIInterfaceOrientation)[[UIDevice currentDevice] orientation];
if(orientation == UIInterfaceOrientationPortrait)
{
isLandscapeMode = NO;
inLandscapeRight = NO;
inLandscapeLeft = NO;
}
else if(orientation == UIInterfaceOrientationLandscapeRight)
{
isLandscapeMode = YES;
inLandscapeRight = YES;
inLandscapeLeft = NO;
} else if(orientation == UIInterfaceOrientationLandscapeLeft)
{
isLandscapeMode = YES;
inLandscapeRight = NO;
inLandscapeLeft = YES;
}
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)
{
isLandscapeMode = YES;
inLandscapeLeft = YES;
inLandscapeRight = NO;
frameForProfile = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
}
else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
{
isLandscapeMode = YES;
inLandscapeLeft = NO;
inLandscapeRight = YES;
frameForProfile = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
}
else
{
isLandscapeMode = NO;
inLandscapeLeft = NO;
inLandscapeRight = NO;
}
}
.
Установите BOOL в соответствии с вашими требованиями
От вас Скриншоты Я вижу, что ваше приложение является базой вкладка.Несколько дней назад я столкнулся с той же проблемой.Я решил это.Я задал вопрос почти то же самое к вашему.Затем через несколько часов чтения я решил проблему.Есть ссылка на My Вопрос и ответ .
По SO есть много похожих вопросов и ответов, но почему-то ни один из них мне не помог, так как мне нужно было разрешить только портретный режим на iPhone, и только ландшафтный режим на iPad, поэтому делюсь своим решением:
Удалите все методы, связанные с ориентацией устройства (
shouldAutoRotate, supportedInterfaceOrientations, preferredInterfaceOrientations
, и т. д.), поскольку они могут конфликтовать друг с другом.В настройках проекта включите все 4 режима:Портрет, Перевернутый, Пейзаж слева, Пейзаж справа
Выберите метод определения типа устройства (iPhone или iPad).Я использую
UIScreen.mainScreen().bounds.height which
не идеален, но соответствует моим потребностямПоместите следующее в AppDelegate
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask { if UIScreen.mainScreen().bounds.height < 760 { //iPhone UIApplication.sharedApplication().setStatusBarOrientation(.Portrait, animated: false); return UIInterfaceOrientationMask.Portrait; } else { UIApplication.sharedApplication().setStatusBarOrientation(.LandscapeLeft, animated: false); return UIInterfaceOrientationMask.Landscape; } }
Протестировано на Xcode 7.1.1 для всех симуляторов iPhone и iPad под управлением iOS9.1.