首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 子視圖控制器導航失效:需透過父視圖控制器 Push

     編輯:程式設計綜合問答

問題

將 EventNameViewController 的 view 作為子視圖加入父視圖,其內部按鈕呼叫 pushViewController 無效果。

原因

子視圖控制器 不在導航控制器堆疊中,self.navigationController 為 nil。

解決方案:Delegate 模式回調父控制器

// 子視圖控制器
@protocol EventNameViewDelegate 
- (void)eventNameViewDidSelectNext:(UIViewController *)nextVC;
@end

@interface EventNameViewController : UIViewController
@property (weak) id delegate;
@end

// 父視圖控制器實現代理
- (void)eventNameViewDidSelectNext:(UIViewController *)nextVC {
    [self.navigationController pushViewController:nextVC animated:YES];
}

// 子視圖按鈕動作
- (IBAction)nextButtonTapped {
    NextViewController *next = [[NextViewController alloc] init];
    [self.delegate eventNameViewDidSelectNext:next];
}

替代方案:Container View Controller (iOS 5+)

// 父視圖控制器
[self addChildViewController:childVC];
[self.containerView addSubview:childVC.view];
[childVC didMoveToParentViewController:self];

// 此時 childVC.navigationController 指向父視圖的 navigationController
// 可直接 [self.navigationController pushViewController:next animated:YES];

關鍵點

  • 單純 addSubview:child.view 不建立父子控制器關係
  • 必須呼叫 addChildViewController: + didMoveToParentViewController:
  • 或用代理模式由父控制器統一處理導航
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved