Portrait support set in project configuration
Configuration appdelegate
1. Add a property to appdelegate.h
@property (nonatomic, assign) BOOL allowRotation;
Copy the code
2. Add two methods to the. M file
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if (self.allowRotation) { return UIInterfaceOrientationMaskAll; }else{ return (UIInterfaceOrientationMaskPortrait); - (BOOL)shouldAutorotate {if (self.allowRotation) {return YES; } return NO; }Copy the code
3. Add code to the specified ViewController
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;
}
Copy the code
4. To return to portrait when exiting the current screen, add code when the controller is about to disappear
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; appDelegate.allowRotation = NO; if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) { [self orientationToPortrait:UIInterfaceOrientationPortrait]; }}Copy the code
5. Horizontal and vertical screens do not work to prevent device switching
-(void)orientationToPortrait:(UIInterfaceOrientation)orientation{SEL seletor = NSSelectorFromString(@"setOrientation:"); NSInvocation *invocatino = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:seletor]]; [invocatino setSelector:seletor]; [invocatino setTarget:[UIDevice currentDevice]]; UIInterfaceOrientation val = orientation; [invocatino setArgument:&val atIndex:2]; [invocatino invoke]; }Copy the code
Listen for vertical and horizontal switching
1. Add notification codes
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];Copy the code
2. Handle the notification type
- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation { UIDevice *device = [UIDevice currentDevice]; The switch (device. Orientation) {case UIDeviceOrientationLandscapeLeft: NSLog (@ "screen placed horizontally to the left"); break; Case UIDeviceOrientationLandscapeRight: NSLog (@ "screen placed horizontally to the right"); break; Case UIDeviceOrientationPortrait: NSLog (@ "screen upright"); break; Case UIDeviceOrientationPortraitUpsideDown: NSLog (@ "screen upright, upside down"); break; Default: NSLog(@" unrecognizable "); break; }}Copy the code