验证了很多网上介绍的方法,基本上分为两类:
(2)方法二的实例:
方法一:旋转视图,然后重新绘画view;
方法二:使用一个已经被apple放弃的私有API函数”setOrientation”(详见参考资料),实现旋转视图;
(1)方法一的实例:
[[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationPortrait animated: YES];
self.navigationController.view.transform = CGAffineTransformIdentity;
self.navigationController.view.transform = CGAffineTransformMakeRotation(M_PI*2);
self.navigationController.view.bounds = CGRectMake(self.navigationController.view.bounds.origin.x,
self.navigationController.view.bounds.origin.y,
self.view.frame.size.height,
self.view.frame.size.width);
调试结果:虽然实现了切换为竖屏,但是视图已经偏移到手机界面外了。实验了很多次,都没有能够调试出想要的效果。
(2)方法二的实例:
// Force main view to Portrait
if(UIDeviceOrientationIsLandscape(self.interfaceOrientation)) {
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
objc_msgSend([UIDevice currentDevice], @selector(setOrientation:), UIInterfaceOrientationPortrait);
}
}
备注:由于需要调用方法“objc_msgSend”,故需要包含下面的头文件:
#import <objc/message.h>
调试结果:调试一次,就能实现需求。方法二的风险:因为调用了apple的一个私有API,可能在APP上架apple store被审核不通过(备注:有待实际验证)。
后记:为什么apple不提供一个官方的方法呢?害得我为了实现这么一个简单的需求,到处搜罗实现方法!