該示例是想在手機屏幕方向發生改變時重新定位視圖(這里是一個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];
}