对于刚接触ipad/iPhone编程的人来说,控制其显示方向是挺纠结的!下面我来给大家详细讲讲这应该是如何控制的。
相信很多人都是,我要控制其横向显示不是很简单,直接在代码里的
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
函数里控制其显示方向不就行了?并且网上也有很多这方面的教程也是这么说的!
那好,那么我们新建一个工程,在其AppDelegate.m里添加下面的代码
控制横向【在网上搜索,相信大家都能得到如何代码控制其横向显示效果的代码】
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) { return YES; } else { return NO; } }大家可以在这里下载这个工程:http://download.csdn.net/detail/comeontom/4299902 当然,也可以自己写,毕竟这个也不难
然后在ViewController.m里添加一张图片:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIImageView * test = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sleep.jpg"]]; [self.view addSubview:test]; }好了,那现在我们来看看其显示效果吧!
当我在虚拟机里让设备是竖向时,其显示效果是:
当屏幕是横向时,显示效果如下:
显然,横向时的效果是我们想要的,但是,当屏幕竖向时,为什么图片是横向的,但是,显示屏的下面是白色的,这肯定不是我们想要的效果。那我们该怎么办呢?
下面是我解决的方案:
点击:
然后看到:
然后将分别点击LandscapeLeft和LandscapeRight【这是初始化设备的显示方向】,如下图:
这些弄好了,我们在看看竖向的显示效果怎么样:
效果还是这样,怎么回事呢?
经过一番思考后,我们只要在ViewController.m里在控制其显示方向就可以了,在里面添加下面的代码:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) { return YES; } else { return NO; } }现在再看看效果是怎么样的:
哈哈,成功了...
总结:
一:控制iPad/iPhone的方向是在类中的方法:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
控制的。
二:如果我们想控制模拟器的初始化方向,可以控制下面的四个按钮
三,控制竖向的代码是:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){ return YES; } else { return NO; } }