在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;
}
}
}
本文介绍了一个iOS应用如何通过监听设备的方向变化来更新UI元素的方法。具体实现包括在viewWillAppear方法中启动方向变化通知监听,定义一个label作为显示方向变化信息的载体,并在收到方向变化通知时更新label内容。
2343

被折叠的 条评论
为什么被折叠?



