先在target中设置成只允许竖屏,这样系统就不会根据重力方向调整屏幕方向了
然后再appdelegate中添加下方的方法。
//appdelegate.h
@property (nonatomic, assign) BOOL isFlip;
//appdelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.isFlip) {
return UIInterfaceOrientationMaskLandscape;
}
return UIInterfaceOrientationMaskPortrait;
}
这里在APPdelegate中声明了手动旋转的方式,当isflip为yes的时候,横屏,no时竖屏。
然后再需要旋转屏幕的方法中插入如下代码
QNAppDelegate *appDelegate = (QNAppDelegate *)[UIApplication sharedApplication].delegate;
//isLandscape 横屏时候为yes,竖屏的时候为no,实际上是在其他地方通过button手动修改的
appDelegate.isFlip = isLandscape;
[appDelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
[UIViewController attemptRotationToDeviceOrientation];
然后下方再写入其他的代码。注意:view的frame或者bounds要做出对应的调整。
另外:[UIViewController attemptRotationToDeviceOrientation];实际上是将self.view及其子view都的坐标都改成旋转后的方向的坐标,放弃系统通过重力方向更改的坐标,如果这个方法放到了末尾,可能导致位置不正确,要先更新self.view的坐标。
例如:当界面处于横屏状态下,手机处于竖直放置(类似于手机看电影时候的竖着拿手机,但是视频是横屏全屏的)时,self.view的坐标在attemptRotationToDeviceOrientation更新前,始终是横屏的坐标,即width是手机的长边。此时更新子view的位置,就会导致获取的self.view的宽高出现错误,发生位置偏移。
NSLog(@"横屏转竖屏前self.view.frame: width:%f,height:%f",self.view.frame.size.width,self.view.frame.size.height);
[UIViewController attemptRotationToDeviceOrientation];
NSLog(@"横屏转竖屏后self.view.frame: width:%f,height:%f",self.view.frame.size.width,self.view.frame.size.height);
运行结果如下:
横屏转竖屏前self.view.frame: width:812.000000,height:375.000000
横屏转竖屏后self.view.frame: width:375.000000,height:812.000000