2010-04-10 26 views
1

我有一個用戶導航的UINavigationController。 將特定UIViewController推入導航堆棧時,navigationBar中會出現一個「settings」按鈕。當用戶單擊此按鈕時,我想將當前的視圖/控制器(即屏幕上的所有內容,包括navigationBar)翻轉到設置視圖。由屬於UINavigationController的UIViewController完成的UIViewAnimation?

所以我有一個SettingsViewController,我想從我的CurrentViewController中翻到導航控制器堆棧上。

我得到各種奇怪的行爲,試圖做到這一點,屬於SettingsViewController的UIViews將開始動畫,滑動到位,navigationButtons四處移動,沒有任何行爲,因爲我會想。

-(void)settingsHandler { 

    SettingViewController *settingsView = [[SettingViewController alloc] init]; 

    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight 
          forView:self.navigationController.view 
          cache:YES]; 

    [self.navigationController.view addSubview:settingsView.view]; 

    [UIView commitAnimations]; 

} 

在視圖上述結果正確地翻轉,但SettingsViewController的子視圖都定位在(0,0),在轉換後,它們「嵌入」到位?

是因爲我實例化並在viewDidLoad中添加我的子視圖,像這樣?

- (void)viewDidLoad { 

    UIImageView *imageBg = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)]; 
    [imageBg setImage:[UIImage imageNamed:@"background.png"]]; 
    [self.view addSubview:imageBg]; 
    [imageBg release]; 

    SettingsSubview *switchView = [[SettingsSubview alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)]; 
    [self.view addSubview:switchView]; 
    [switchView release]; 
    [super viewDidLoad]; 
} 

1:我應該如何正確地做了「翻轉」過渡,從UIViewController中的UINavigationController的範圍內,一個新的UIViewController,然後從新的UIViewController,並回到「原始」的UIViewController駐留在UINavigationControllers堆棧?

2:在實例化和添加子視圖到UIViewController時,我應該使用不同的方法,比「viewDidLoad」方法嗎?

-question 2更像是一個「最佳實踐」的東西。我看到了不同的方式 這樣做,我無法找到或理解生命週期文檔和主題上的不同主題和帖子。我錯過了「最佳實踐」的例子。

非常感謝你的。如果你想以編程方式創建視圖層次,做到這一點是-loadView的地方給予:)

回答

3

任何幫助。要做到這一點,你必須自己創建的視圖中,添加所有的子視圖,然後將其分配給視圖屬性,像這樣:

- (void)loadView { 
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)]; 

    UIImageView *imageBg = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)]; 
    [imageBg setImage:[UIImage imageNamed:@"background.png"]]; 
    [containerView addSubview:imageBg]; 
    [imageBg release]; 

    SettingsSubview *switchView = [[SettingsSubview alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)]; 
    [containerView addSubview:switchView]; 
    [switchView release]; 

    self.view = containerView; 
    [containerView release]; 
} 

它有助於瞭解在調用此方法的背景下,如何它的行爲默認。第一次訪問UIViewController的視圖屬性時,默認的getter方法調用-loadView來延遲加載視圖。 -loadView的默認實現將從nib加載視圖(如果指定了該視圖)。否則,它會創建一個普通的UIView對象並將其設置爲控制器的視圖。通過重寫此方法,您可以確保您的視圖的層次結構在第一次訪問時完全形成。

-viewDidLoad應該用於在視圖層次結構完全加載後需要發生的任何後續設置。該方法將調用視圖是否從nib加載或在loadView中以編程方式構造。

+0

謝謝cduhn。 這是一個很好的解釋和完美的例子。 – RickiG 2010-04-11 19:30:58

相關問題