您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 橫竖屏適配方案(二):加載不同的 View

編輯:iOS 開發綜合

方法一:橫竖屏分別加載兩個不同的 View(手寫 View)

在旋轉時切換 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];
}

方法二:在一個 XIB 裡添加兩個不同的 View

這種做法只需要改變兩個 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 則更直觀,適合界面元素重複度高、僅尺寸不同的情況。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved