LoginSignup
3
2

More than 1 year has passed since last update.

【SwiftUI】SPMを利用したマルチモジュールにおけるモジュール間の画面遷移

Last updated at Posted at 2022-05-02

マルチモジュールでのモジュール間の画面遷移について調べていたところ、以下の記事が良さそうだったので、そちらを参考に実装してみました.
簡単な説明とサンプルコードを記載します.

前提

  • FeatureA, FeatureBというモジュールを作成
  • 循環参照を避けるため、それぞれ依存関係にない(お互いの存在を知らない) 状態

やりたいこと

FeatureAのView から FeatureBのViewへと画面遷移したい

ただ、FeatureAは、FeatureBの存在を知らないのでそのままFeatureBをimportして画面遷移させることはできないので、DIを利用して画面遷移を実現

実装

ViewDiscriptorの作成

どのモジュールからでもアクセスできる CoreModules内に作成.
ここに遷移先の情報を列挙していきます.
必要なパラメータ、返ってくる型などの情報をもつ.

ViewResoverの作成

DIコンテナの役割をする Environment の protocol.
CoreModules内に作成し、画面遷移する際に FeatureModules内で利用.

SampleEnvironmentの作成

DIコンテナの役割.
FeatureModule内で、EnvironmentにDescriptorを渡し、遷移先のViewを要求.

画面遷移

画面遷移は以下のように実装します.

public struct FeatureA: View {
    var environment: ViewResolver
    public init(resolver: ViewResolver) { self.environment = resolver }
    
    public var body: some View {
        NavigationView {
            VStack {
                Text("FeatureA")
                NavigationLink("Next", destination: environment.resolveConcrete(ViewDescriptor.FeatureBDescriptor(text: "FeatureB")))
            }
        }
    }
}

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2