一、需求
- 很多朋友都需要在view或在其工具類中拿到當(dāng)前顯示的控制器去操作
二、解決辦法
- 第一種:可以通過參數(shù),將當(dāng)前顯示的控制器傳入view或者工具類中(不建議)
- 第二種:就是我下面介紹的方法,給NSObject添加分類,此時(shí)不管是view還是工具類,都能獲取當(dāng)前顯示的控制器
三、效果圖(跳轉(zhuǎn)效果都是在view中實(shí)現(xiàn))
view中跳轉(zhuǎn)
四、API及用法
-
API : 獲取當(dāng)前控制器,不管你是modal過來還是push過來,內(nèi)部已經(jīng)處理了
/**
* @author Clarence
*
* 獲取當(dāng)前顯示的控制器
*/
- (UIViewController *)fl_viewController;
-
用法一: modal調(diào)用
- (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 調(diào)用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.fl_viewController.navigationController pushViewController:[[FLThirdViewController alloc] init] animated:YES];
}
五、總結(jié)(看法)
說實(shí)話,我很不贊成這種做法,因?yàn)檫@樣不面向?qū)ο螅D(zhuǎn)邏輯等操作應(yīng)該是在控制器中處理的,因此才有代理的出現(xiàn),view只負(fù)責(zé)拿到model數(shù)據(jù)進(jìn)行顯示,當(dāng)然還是可以處理部分邏輯的,工具類另談
在view中,不建議拿到當(dāng)前的控制器去實(shí)現(xiàn)跳轉(zhuǎn)等操作,建議按照蘋果的做法,可以利用代理、block或者通知去實(shí)現(xiàn)。
在NSObject工具類中,既然是工具,就是用來處理大部分的邏輯操作,跳轉(zhuǎn)操作當(dāng)然也可以封裝在內(nèi)部,減輕控制器的負(fù)擔(dān),類似MVVM的做法了,這里就不談MVVM了,以后有機(jī)會(huì)我會(huì)另開一篇介紹。