最近做了一点关于屏幕旋转的东西,第一次做,搞的焦头烂额,所幸在同事的帮助下完成了,现在记录一下,便于以后查看。
1.首先需要在General里,Deployment info 里根据自己的需求设置Device Orientation。
Portrait代表竖屏Landscape代表横屏
2.如果是想要自动根据手机的方向横竖屏的话设置下面两个方法
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
3如果想手动控制横竖屏,就用下面的方法
添加按钮的方法
[UIDevice currentDevice] orientation]可以取到当前屏幕的方向
if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait)
{
[self setfullScreen];
}
if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft)
{
[self setsmallScreen];
//横屏
- (void)setfullScreen
{
[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}
//竖屏
- (void)setsmallScreen
{
[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationPortrait] forKey:@"orientation"];
}
然后旋转后的frame需要根据自己需要设置
还有一种横屏方法为强制横屏,在view上添加一个window,然后把window强制旋转,但是这样做键盘还是竖屏,可以根据需要选择
下面直接上方法
- (void)setLandScapeViewWithOrientation:(UIDeviceOrientation)orientnation
{
if (UIDeviceOrientationIsLandscape(orientnation)) {
if (_landScapeWindow == nil) {
CGRect screenFrame = [UIScreen mainScreen].bounds;
_landScapeWindow = [[UIWindow alloc] initWithFrame:CGRectMake(screenFrame.size.width/2 - screenFrame.size.height/2, screenFrame.size.height/2 - screenFrame.size.width/2, screenFrame.size.height, screenFrame.size.width)];
_landScapeWindow.windowLevel = UIWindowLevelStatusBar + 1;
_landScapeWindow.center = CGPointMake(screenFrame.size.width/2, screenFrame.size.height/2);
CGFloat angle = M_PI_2;
if (orientnation == UIDeviceOrientationLandscapeRight) {
angle = M_PI_2 + M_PI;
}
_landScapeWindow.transform = CGAffineTransformIdentity;
_landScapeWindow.transform = CGAffineTransformMakeRotation(angle);
_landScapeWindow.hidden = NO;
} else if (UIDeviceOrientationIsPortrait(orientnation)) {
_landScapeWindow.hidden = YES;
}
}
}