Skip to content

Instantly share code, notes, and snippets.

@alexbartisro
Created May 18, 2020 08:56
Show Gist options
  • Save alexbartisro/9e9742e5e3b1663d568bc9dc71dcb0c7 to your computer and use it in GitHub Desktop.
Save alexbartisro/9e9742e5e3b1663d568bc9dc71dcb0c7 to your computer and use it in GitHub Desktop.
Passing closures between SwiftUI sibling views
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