该示例是想在手机屏幕方向发生改变时重新定位视图(这里是一个button)
1.创建一个View—based Application项目,并在View窗口中添加一个Round Rect Button视图,通过尺寸检查器设置其位置,然后单击View窗口右上角的箭头图标来旋转窗口方向,重新定位button,这两个位置随便定义,只要能区分在不同位置即可,记住这两个位置的数据,因为在代码里面会用到。
2.在.h头文件里面定一个UIButton,并添加两个方法,后面会解释这两个方法:
- #import <UIKit/UIKit.h>
- @interface ChangeOrientation : UIViewController {
- IBOutlet UIButton *mybutton;
- }
- @property(nonatomic,retain)UIButton *mybutton;
- -(void)positionViews;
- -(IBAction)makeChange;
- @end
#import <UIKit/UIKit.h>
@interface ChangeOrientation : UIViewController {
IBOutlet UIButton *mybutton;
}
@property(nonatomic,retain)UIButton *mybutton;
-(void)positionViews;
-(IBAction)makeChange;
@end
3.要向让手机支持所有旋转方向,必须修改自动生成的方法,让其return YES:
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return YES;
- }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
4.添加一个根据当前屏幕的方向改变button位置的方法,该方法在.h头文件定义过:
- //根据当前的屏幕方向改变button的位置
- -(void)positionViews{
- UIInterfaceOrientation destorientation = self.interfaceOrientation;
- if (destorientation == UIInterfaceOrientationPortrait ||
- destorientation == UIInterfaceOrientationPortraitUpsideDown) {
- mybutton.frame = CGRectMake(20, 20, 233, 37);
- }else{
- mybutton.frame = CGRectMake(227, 243, 233, 37);
- }
- }
//根据当前的屏幕方向改变button的位置
-(void)positionViews{
UIInterfaceOrientation destorientation = self.interfaceOrientation;
if (destorientation == UIInterfaceOrientationPortrait ||
destorientation == UIInterfaceOrientationPortraitUpsideDown) {
mybutton.frame = CGRectMake(20, 20, 233, 37);
}else{
mybutton.frame = CGRectMake(227, 243, 233, 37);
}
}
5.当屏幕正在旋转的时候需要处理如下事件,这样就可以调用前面定义的方法positionViews方法改变button的位置:
(补充:willAnimateFirstHalfOfRotationToInterfaceOrientation:事件是在View窗口开始旋转前促发)
- //当屏幕旋转到一半的时候促发的方法
- -(void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration{
- [self positionViews];
- }
//当屏幕旋转到一半的时候促发的方法
-(void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration{
[self positionViews];
}
6.在窗口加载完毕后调用positionViews方法来定位当前屏幕方向的button的位置:
- - (void)viewDidLoad
- {
- [self positionViews];
- [super viewDidLoad];
- }
- (void)viewDidLoad
{
[self positionViews];
[super viewDidLoad];
}
7.添加一个button点击方法(该方法在.h头文件中定义过),当点击这个button的时候动态改变屏幕的方向,代码如下:
- //点击button动态改变屏幕方向
- -(IBAction)makeChange{
- [[UIDevice currentDevice]setOrientation:UIInterfaceOrientationLandscapeLeft];
- }
//点击button动态改变屏幕方向
-(IBAction)makeChange{
[[UIDevice currentDevice]setOrientation:UIInterfaceOrientationLandscapeLeft];
}