0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swiftui]A画面→B画面でA画面のメソッドをコールする

Posted at

タイトルの通り、呼び出し元A画面からB画面をNavigationLinkで遷移してB画面を開いているところから、A画面のメソッドを呼びたいときの方法です。
ここら辺はinterfaceの概念でlistenerの仕組みを使うと呼び出すことができます。
この考え方はjavaなどのレガシー言語と考え方は同じ。
もしこの考えを知らない人は勉強しなおしてください。

要点がわかるように最小限のコードサンプルです。

protocol Listener {
    func method()
}

struct ContentView: View, Listener {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: NextView(listener: self)) {
                    Text("next view")
                }
            }
        }
    }
    
    func method {
        // do-something
    }
}

struct NextView: View {
    var listener: Listener
    var body: some View {
        Button(action: {
            self.listener.method()
        }) {
            Text("first view method call")
        }
    }
}

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?