在Viewdidload中新建一个label,并且定义成全局变量,便于下面方法的调用;通过该实例可以感应到设备的方向
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];[[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(rece:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self];
[[UIDevice currentDevice]endGeneratingDeviceOrientationNotifications];
}
- (void)rece:(NSNotification *)not{
UIDevice *device = [UIDevice currentDevice];
switch (device.orientation) {
case UIDeviceOrientationUnknown: {
label.text = @"竖直向上";
break;
}
case UIDeviceOrientationPortrait: {
label.text = @"竖直向下";
break;
}
case UIDeviceOrientationPortraitUpsideDown: {
label.text = @"水平向左";
break;
}
case UIDeviceOrientationLandscapeLeft: {
label.text = @"水平向右";
break;
}
case UIDeviceOrientationLandscapeRight: {
label.text = @"面朝上";
break;
}
case UIDeviceOrientationFaceUp: {
label.text = @"面朝下";
break;
}
case UIDeviceOrientationFaceDown: {
label.text = @"未知";
break;
}
default: {
break;
}
}
}