Delegate pattern between views. It is also a sample of page transition using NavigationLink.
The repository is here> https://github.com/dropcontrol/ViewControllerDelegatePattern This article itself is the same as README.md in the repository.
TL;DR
A pattern that passes values between views. Two views are prepared. Implemented two patterns, one is passed from parent to child and the other is passed from child to parent. I think there are other ways to pass values, but this is the most basic pattern.
Add the following to the child SecondView.swift
let text: String = "Not Success" //Initial value required
In this case, since it is called from the parent using Navigation Link, the character string is passed to text in SecondView () registered in destination.
NavigationLink(
destination: SecondView(delegate: self, text: "Sucess send message"),
label: {
Text("Go to SecondView")
})
Delegate will be explained in the case of passing from the following child to the parent, but the transition destination View and its delegate can be called for each destination of NavigationLink.
I think this pattern is often used. It is implemented by the delegate pattern.
protocol secondViewDelegate {
func returnData(text: String)
}
struct SecondView: View {
var delegate: secondViewDelegate?
Button(action: {
self.delegate?.returnData(text: "Success!!")
self.presentation.wrappedValue.dismiss()
}, label: {
Text("Try delegate")
})
struct ContentView: View, secondViewDelegate{
NavigationLink(
destination: SecondView(delegate: self, text: "Sucess send message"),
@State
.@State var text: String = "not change yet"
func returnData(text: String) {
self.text = text
}
@Environment
is an environment variable in SwiftUI that allows you to monitor and change the status in various ways. Create a variable in SecondView.swift below.
@Environment(\.presentationMode) var presentation
Now that you have the presentationMode environment variable,
Button(action: {
self.delegate?.returnData(text: "Success!!")
self.presentation.wrappedValue.dismiss()
You can close the screen by calling self.presentation.wrappedValue.dismiss ()
. This is the same for other screen transitions (eg modal view).
You can read more about @Environment
in this article.
https://qiita.com/1amageek/items/59c6bb32a6627b4fb712
Feeling like.
Recommended Posts