Отключить авторотацию на одном UIViewController в iOS6
У меня есть проект с использованием UINavigationController
и segues
, работающих нормально, все они вращаются правильно, дело в том, что... Я просто хочу отключить autorotation
для определенного UIViewController
.
Я пробовал это:
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
return NO;
}
// New Autorotation support for iOS 6.
- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0){
return NO;
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
но он не работает, мой UIViewController
продолжает вращаться автоматически, любая помощь будет приветствоваться:)
Ответы
Ответ 1
В руководстве по программированию контроллера просмотра
Если вы хотите временно отключить автоматическое вращение, не делайте этого с помощью масок ориентации. Вместо этого переопределите метод shouldAutorotate на начальном контроллере представления. Этот метод вызывается перед выполнением любой авторотации. Если он возвращает NO, тогда вращение будет подавлено.
Итак, вам нужно подклассировать "UINavigationController", реализовать shouldAutorotate и использовать свой класс контроллера навигации в своем раскадровке.
- (BOOL)shouldAutorotate
{
id currentViewController = self.topViewController;
if ([currentViewController isKindOfClass:[DetailViewController class]])
return NO;
return YES;
}
Ответ 2
Собираем ответ GayleDDS для новичков
просто добавил подкласс UINavigationController, как он предложил следующее:
#import "UINavigationController.h"
#import "MonthCalendarVC.h"
@implementation UINavigationController (overrides)
- (BOOL)shouldAutorotate
{
id currentViewController = self.topViewController;
if ([currentViewController isKindOfClass:[MonthCalendarVC class]])
return NO;
return YES;
}
@end
MonthCalendarVC - это viewController. Я хочу быть только в портретном режиме (исправлено), а затем просто добавил импорт в мой appdelegate.m
#import "UINavigationController.h"
и что он
Ответ 3
Взгляните на этот другой подход:
http://www.sebastianborggrewe.de/only-make-one-single-view-controller-rotate/
Вам просто нужно реализовать canRotate в ViewController, чтобы разрешить поворот.
Прекрасно работает на iOS 7.
2015-01-30
Поскольку сайт sebastian, похоже, не работает (ошибка 404), это моя интерпретация его решения:
В отличие от себастьяна, я предпочитаю использовать протокол (например, интерфейс на С#), чтобы избежать создания метода "- (void) canrotate:" в каждом из моих контроллеров представления.
IRotationCapabilities.h
-----------------------
#ifndef NICE_APPS_IRotationCapabilities_h
#define NICE_APPS_IRotationCapabilities_h
@protocol IRotationCapabilities < NSObject >
// Empty protocol
@end
#endif
FirstViewController.h
---------------------
- ( void )viewWillAppear:( BOOL )animated
{
[ super viewWillAppear:animated ];
// Forces the portrait orientation, if needed
if( ![ self conformsToProtocol:@protocol( IRotationCapabilities ) ] )
{
if( self.navigationController.interfaceOrientation != UIInterfaceOrientationPortrait )
{
[ [ UIDevice currentDevice ] setValue:@( 1 ) forKey:@"orientation" ];
}
}
}
SecondViewController.h
-----------------------
#import "IRotationCapabilities.h"
@interface SecondViewController : UIViewController < IRotationCapabilities >
AppDelegate.m
-------------
#pragma mark - Orientation management
- ( NSUInteger )application:( UIApplication * )application supportedInterfaceOrientationsForWindow:( UIWindow * )window
{
if( __iPhone )
{
// Gets topmost/visible view controller
UIViewController * currentViewController = [ self topViewController ];
// Checks whether it implements rotation
if( [ currentViewController conformsToProtocol:@protocol( IRotationCapabilities ) ] )
{
// Unlock landscape view orientations for this view controller
return ( UIInterfaceOrientationMaskAllButUpsideDown );
}
// Allows only portrait orientation (standard behavior)
return ( UIInterfaceOrientationMaskPortrait );
}
else
{
// Unlock landscape view orientations for iPad
return ( UIInterfaceOrientationMaskAll );
}
}
Ответ 4
Попробуйте реализовать это в своем UIViewController:
// implements the interface orientation (iOS 6.x)
@interface UINavigationController (RotationNone)
-(NSUInteger)supportedInterfaceOrientations;
@end
@implementation UINavigationController (RotationNone)
-(NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
@end
Ответ 5
Я вижу, что кто-то спросил об этом в Swift. Это не сразу очевидно, так как методы Objective-C вовсе не являются методами в Swift, а скорее вычисляются как переменные:
override var shouldAutorotate: Bool { return false }
override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }