Created
May 18, 2020 08:56
-
-
Save alexbartisro/9e9742e5e3b1663d568bc9dc71dcb0c7 to your computer and use it in GitHub Desktop.
Passing closures between SwiftUI sibling views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
import PlaygroundSupport | |
typealias OnClickHandler = (() -> Void) | |
struct ParentView: View { | |
@State var onClick: OnClickHandler = { } | |
var body: some View { | |
VStack { | |
ChildView1(onClick: $onClick) | |
Spacer() | |
ChildView2(onClick: $onClick) | |
} | |
} | |
} | |
struct ChildView1: View { | |
@Binding var onClick: OnClickHandler | |
@State var titleText = "We love closures" | |
var body: some View { | |
Text(titleText).onAppear { | |
self.onClick = self.doMagic | |
} | |
} | |
private func doMagic() { | |
print("We love closures") | |
titleText = "But in a platonic way" | |
} | |
} | |
struct ChildView2: View { | |
@Binding var onClick: OnClickHandler | |
var body: some View { | |
Button(action: onClick) { | |
Text("Tap me and then just hurt me") | |
} | |
} | |
} | |
PlaygroundPage.current.setLiveView(ParentView()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment