在旋轉時切換 portrait 與 landscape 兩個 view:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
[landscape removeFromSuperview];
[self.view addSubview:portrait];
}
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
[portrait removeFromSuperview];
[self.view addSubview:landscape];
}
}
// 以程式碼建立 view 層級,不使用 nib
- (void)loadView {
UIControl *back = [[UIControl alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
back.backgroundColor = [UIColor grayColor];
self.view = back;
[back release];
}
- (void)viewDidLoad {
[super viewDidLoad];
portrait = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 440)];
portrait.backgroundColor = [UIColor yellowColor];
landscape = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 460, 280)];
landscape.backgroundColor = [UIColor greenColor];
[self.view addSubview:portrait];
}
這種做法只需要改變兩個 view 裡面控制項的尺寸,而動作事件是共用的:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
[self.landscapeView removeFromSuperview];
[self.view addSubview:self.portraitView];
}
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
[self.portraitView removeFromSuperview];
[self.view addSubview:self.landscapeView];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.portraitView];
}
兩種做法各有取捨:手寫 view 靈活可控,適合需要精細定制布局的場景;而在同一個 XIB 中放置兩個 view 則更直觀,適合界面元素重複度高、僅尺寸不同的情況。