BSTwoControllerView實現兩個控制器的切換
阿新 • • 發佈:2018-11-01
需求
點選按鈕實現兩個介面的切換,如果用一個controller管理,那麼程式碼顯得過於龐大。這時候用BSTwoControllerView可以優雅的把程式碼分在兩個controller來管理。
效果
- 點選OneVC按鈕切換至OneVC控制器,點選TwoVC按鈕切換至TwoVC控制器。
- github地址: https://github.com/FreeBaiShun/BSTwoControllerView
用法
- pod ‘BSTwoControllerView’
- 編寫程式碼
#import "ViewController.h" #import "OneVC.h" #import "TwoVC.h" #import "BSTwoControllerView/BSTwoControllerView.h" @interface ViewController () @property (weak, nonatomic) IBOutlet BSTwoControllerView *viewBottom; @end @implementation ViewController{ OneVC *oneVC; TwoVC *twoVC; } - (void)viewDidLoad { [super viewDidLoad]; oneVC = [OneVC new]; twoVC = [TwoVC new]; [self.viewBottom initTwoControllerWithMainController:self controller1:oneVC controller2:twoVC]; } - (IBAction)btnOneVC:(id)sender { [self.viewBottom setDisplayWithController:oneVC]; } - (IBAction)btnTwoVC:(id)sender { [self.viewBottom setDisplayWithController:twoVC]; } @end
程式碼分析
-
initTwoControllerWithMainController作為初始化程式碼
- (void)initTwoControllerWithMainController:(UIViewController *)mainController controller1:(UIViewController *)controller1 controller2:(UIViewController *)controller2{ __weak typeof (self) weakeSelf = self; weakeSelf.mainController = mainController; [mainController addChildViewController:controller1]; controller1.view.frame = self.bounds; [weakeSelf addSubview:controller1.view]; [mainController addChildViewController:controller2]; weakeSelf.controllerCur = controller1; [controller1.view.superview layoutIfNeeded]; }
- mainController新增子控制器controller1。修改controller1的frame修改,並新增其view這樣會實現走controller1的viewDidLoad方法。
- mainController新增子控制器controller2儲存當前的控制器為controller1。
-
setDisplayWithController切換控制器方法
- (void)setDisplayWithController:(UIViewController *)controller{ if (_controllerCur != controller) { controller.view.frame = self.bounds; __weak typeof (self) weakeSelf = self; [_mainController transitionFromViewController:_controllerCur toViewController:controller duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:^(BOOL finished) { if (finished) { weakeSelf.controllerCur = controller; } }]; } }
- controller.view.frame修改當前要切換的控制器的view大小。
- 呼叫transitionFromViewController方法實現控制器的切換,當切換完成時候儲存當前控制器即可