处理iOS设备的屏幕旋转

时间:2023-03-09 18:10:41
处理iOS设备的屏幕旋转

某些情况下,不强制的给用户唯一的屏幕角度给用户。这样用户可以旋转手机得到不同的视觉体验。

最简单的就是safari,横看竖看都可以。

这时需要捕捉用户的屏幕旋转事件并处理。很简单,才两步。比把大象装冰箱都简单。

下面是代码:

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
}
return self;
}

在ViewController初始化或者viewDidLoad方法中加入Notification就可以。很显然,Post Notification的事苹果的SDK已经为我们

处理了。我们代码中要做的就是处理发送来的Notification。

添加好Notification的Observer后就剩添加具体的处理方法了。这里就是orientationChanged。

 - (void)orientationChanged:(NSNotification *)notification{
UIDevice * device = notification.object;
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
/* start special animation */
break; case UIDeviceOrientationPortraitUpsideDown:
/* start special animation */
break; default:
break;
};
}

接下来就在switch-case语句里针对没一种屏幕可能的角度添加你的处理代码吧。