Skip to content

Instantly share code, notes, and snippets.

@kingiol
Created November 10, 2015 09:51
Show Gist options
  • Save kingiol/a0e851acb046e066ff30 to your computer and use it in GitHub Desktop.
Save kingiol/a0e851acb046e066ff30 to your computer and use it in GitHub Desktop.
监听手机当前的方向
UIDevice *device = [UIDevice currentDevice]; //Get the device object
[device beginGeneratingDeviceOrientationNotifications]; //Tell it to start monitoring the accelerometer for orientation
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; //Get the notification centre for the app
[nc addObserver:self //Add yourself as an observer
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:device];
- (void)orientationChanged:(NSNotification *)note
{
//[self setNeedsStatusBarAppearanceUpdate];
CGRect screenBounds = [UIScreen mainScreen].bounds;
[UIView beginAnimations:nil context:nil];
self.navigationController.view.transform = CGAffineTransformIdentity;
switch ([[UIDevice currentDevice] orientation]) {
case UIDeviceOrientationUnknown:
case UIDeviceOrientationPortrait:
case UIDeviceOrientationPortraitUpsideDown:
case UIDeviceOrientationFaceUp:
case UIDeviceOrientationFaceDown: { // all Protrait
self.navigationController.view.bounds = screenBounds;
break;
}
case UIDeviceOrientationLandscapeLeft: {
self.navigationController.view.transform = CGAffineTransformMakeRotation(M_PI_2);
CGRect bounds = screenBounds;
bounds.size.width = screenBounds.size.height;
bounds.size.height = screenBounds.size.width;
self.navigationController.view.bounds = bounds;
break;
}
case UIDeviceOrientationLandscapeRight: {
self.navigationController.view.transform = CGAffineTransformMakeRotation(-M_PI_2);
CGRect bounds = screenBounds;
bounds.size.width = screenBounds.size.height;
bounds.size.height = screenBounds.size.width;
self.navigationController.view.bounds = bounds;
break;
}
default: {
break;
}
}
[UIView commitAnimations];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment