一、需求
- 很多朋友都需要在view或在其工具類中拿到當前顯示的控制器去操作
二俱笛、解決辦法
- 第一種:可以通過參數(shù),將當前顯示的控制器傳入view或者工具類中(不建議)
- 第二種:就是我下面介紹的方法踏枣,給NSObject添加分類嫡秕,此時不管是view還是工具類,都能獲取當前顯示的控制器
三枯冈、效果圖(跳轉效果都是在view中實現(xiàn))
view中跳轉
四毅贮、API及用法
-
API : 獲取當前控制器,不管你是modal過來還是push過來尘奏,內部已經處理了
/**
* @author Clarence
*
* 獲取當前顯示的控制器
*/
- (UIViewController *)fl_viewController;
-
用法一: modal調用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
FLSecondViewController *vc = [[FLSecondViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
[self.fl_viewController presentViewController:nav animated:YES completion:nil];
}
-
用法二:push 調用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.fl_viewController.navigationController pushViewController:[[FLThirdViewController alloc] init] animated:YES];
}
五滩褥、總結(看法)
說實話,我很不贊成這種做法炫加,因為這樣不面向對象瑰煎,跳轉邏輯等操作應該是在控制器中處理的,因此才有代理的出現(xiàn)俗孝,view只負責拿到model數(shù)據(jù)進行顯示酒甸,當然還是可以處理部分邏輯的,工具類另談
在view中赋铝,不建議拿到當前的控制器去實現(xiàn)跳轉等操作插勤,建議按照蘋果的做法,可以利用代理、block或者通知去實現(xiàn)农尖。
在NSObject工具類中析恋,既然是工具,就是用來處理大部分的邏輯操作盛卡,跳轉操作當然也可以封裝在內部助隧,減輕控制器的負擔,類似MVVM的做法了滑沧,這里就不談MVVM了并村,以后有機會我會另開一篇介紹。