iOS - Coordinators Pattern的使用

Coordinators模式

一般情况下pushpresent到一个新的vc页面,都是在现有的vc页面创建view controller,设置相应的传递数据,然后进行pushpresent操作

var viewController = BaseViewController()
viewController.data = data
self.navigationController?.pushViewController(viewController, animated: true)       

而且这样形式的代码,项目中随处可见,特别是当一个vc事件多的时候,大量的跳转操作,如下所示

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     guard let type = ContentType(rawValue: indexPath.row) else { return }
     var vc: UIViewController!
     switch type {
     case .tips:
         vc = TipsViewController()
     case .swiftLanguage:
         vc = SwiftLanguageViewController()
     case .newKnowledge:
         vc = NewKnowledgeViewController()
     case .foundation:
         vc = FoundationViewController()
     case .arichtecture:
         vc = ArichtectureViewController()
     case .notification:
         vc = NotificationViewController()
     case .desginPattern:
         vc = DesignPatternViewController()
     case .thread:
         vc = ThreadViewController()
     case .network:
         vc = NetWorkViewController()
     case .framework:
         vc = ThirdFrameworkViewController()
     case .UIkit:
         vc = UIKitViewController()
     case .dataCache:
         vc = DataCacheViewController()
    }
     self.navigationController?.pushViewController(vc, animated: true)
}

这里还比较简单,实际情况更加复杂,因为涉及到值的传递和回调。这会带来一些问题

  • 我们必须硬编码实现一个viewController到另一个viewController的跳转
  • 而且可能会存在重复创建viewController进行跳转的代码,因为一个viewController页面有可能存在多个地方要进入通一个viewController
  • 如果需要在不同的设备使用,那么需要添加一些确认逻辑

Coordinator模式能够帮助我们解决这些问题,把跳转逻辑剥离出来,也不需要进行硬编码操作,而且能够让view controllers进行解耦合,更容易重用

什么是Coordinators?

A Coordinator is an object the encapsulates a lifecycle that is spread over a collection of view controllers.

So what is a coordinator? A coordinator is an object that bosses one or more view controllers around. Taking all of the driving logic out of your view controllers, and moving that stuff one layer up is gonna make your life a lot more awesome.

Soroush Khanlou Coordinators Redux

Coordinator模式简单来说就是分离所有的navigation操作【push/present】到自定义类,由Coordinator控制页面的流向,在自定义类中实现页面之间的切换【当前vc和子vc之间或者子vc和子vc之间的跳转】、包括事件【按钮点击、cell的点击】的处理。每一个功能模块都可以定义一个Coordinator类来处理事件。

比如下图:

截屏2020-05-29 下午4.44.45.png

Coordinator负责创建navigation controller和任意的子视图控制器(child view controllers),子视图控制器完全独立于使用它们的上下文,方便重用和测试

A, B, C 3个vcCoordinator中进行使用,每一个vc都由自己的代理(delegate)来处理交互事件,然后由Coordinator来处理这些事件,执行具体的跳转

Coordinator优点

  • Each view controller is now isolated.
  • View controllers are now reusable.
  • Every task and sub-task in your app now has a dedicated way of being encapsulated.
  • Coordinators separate display-binding from side effects.
  • Coordinators are objects fully in your control.

Souroush Khanlou: Coordinators Redux

2、使用例子

使用Xcode创建一个新工程,创建Coordinator文件,声明Coordinator协议

import UIKit

protocol Coordinator {
    // 存储所有的子Coordinators
    var childCoordinators: [Coordinator] { get set }
    // 存储导航控制器
    var navigationController: UINavigationController { get set }
    // 启动方法
    func start()
}

创建一个Storyboarded文件,定义Storyboarded初始化协议方便获取ViewController,后面会通过Storyboarded布局并加载ViewController

import UIKit

// 定义Storyboarded初始化协议
protocol Storyboarded {
    static func instantiate() -> Self
}

// 通过Storyboard获取vc
extension Storyboarded where Self: UIViewController {
    static func instantiate() -> Self {
        
        let fullName = NSStringFromClass(self)

        // this splits by the dot and uses everything after, giving "MyViewController"
        let className = fullName.components(separatedBy: ".")[1]
        
        // load our storyboard
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        
        // instantiate a view controller with that identifier, and force cast as the type that was requested
        return storyboard.instantiateViewController(withIdentifier: className) as! Self
    }
}

使ViewController实现Storyboarded的协议

import UIKit

class ViewController: UIViewController, Storyboarded {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

打开Main.storyboard进行页面布局,设置ViewControllerstoryboard identifierViewController,方便获取ViewController,取消its Initial View Controller

截屏2020-05-30 上午9.33.06.png

创建MainCoordinator文件,用于启动app

import UIKit

// 控制app整体的流向,实现Coordinator协议
class MainCoordinator: Coordinator {
    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
    }

    func start() {
        // 获取主vc
        let vc = ViewController.instantiate()
        navigationController.pushViewController(vc, animated: false)
    }
}

修改AppDelegate文件

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var coordinator: MainCoordinator?
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // create the main navigation controller to be used for our app
        let navController = UINavigationController()

        // send that into our coordinator so that it can display view controllers
        coordinator = MainCoordinator(navigationController: navController)

        // tell the coordinator to take over control
        coordinator?.start()

        // create a basic UIWindow and activate it
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = navController
        window?.makeKeyAndVisible()

        return true
    }
 ....
}

创建一个BuyViewControllerCreateAccountViewController,进入Main.storyboard拖2个UIViewController,分别指定storyboard identifierBuyViewControllerCreateAccountViewController,简单为两个vc各个添加一个label标识,然后在ViewController上添加两个按钮,分别为BuyfoodCreateAccount,并且添加添加点击事件

截屏2020-05-30 上午8.41.22.png
import UIKit

class ViewController: UIViewController, Storyboarded {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func buyTapped(_ sender: Any) {

    }
    
    @IBAction func createAccount(_ sender: Any) {
        
    }
}

接下来在3个vc中添加coordinator属性

 weak var coordinator: MainCoordinator?

并且让BuyViewControllerCreateAccountViewController遵守Storyboarded协议

import UIKit

class BuyViewController: UIViewController, Storyboarded {

    weak var coordinator: MainCoordinator?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

import UIKit

class CreateAccountViewController: UIViewController, Storyboarded {

    weak var coordinator: MainCoordinator?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

最后实现交互事件,修改MainCoordinator文件

import UIKit

// 控制app整体的流向,实现Coordinator协议
class MainCoordinator: Coordinator {
    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
    }

    func start() {
        // 获取主vc
        let vc = ViewController.instantiate()
        vc.coordinator = self // 设置coordinator
        navigationController.pushViewController(vc, animated: false)
    }
}

// 添加交互事件
extension MainCoordinator {
    func buyFood() {
        let vc = BuyViewController.instantiate()
        vc.coordinator = self
        navigationController.pushViewController(vc, animated: true)
    }

    func createAccount() {
        let vc = CreateAccountViewController.instantiate()
        vc.coordinator = self
        navigationController.pushViewController(vc, animated: true)
    }
}

ViewController使用coordinator执行事件

class ViewController: UIViewController, Storyboarded {

    weak var coordinator: MainCoordinator?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func buyTapped(_ sender: Any) {
        coordinator?.buyFood()
    }
    
    @IBAction func createAccount(_ sender: Any) {
        coordinator?.createAccount()
    }
}

运行效果

11.gif

代码源于 How to use the coordinator pattern in iOS apps,具体内容可以自己阅读

3、coordinator使用的常见问题

  • How and when do you use child coordinators?
  • How do you handle moving back from a navigation controller?
  • How do you pass data between view controllers?
  • How do you use tab bar controllers with coordinators?
  • How do you handle segues?
  • How do you use protocols or closures instead?

具体可参考 Advanced coordinators in iOS

参考

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349