My ContentView has one View (RightView) inside. Tapping the button over RightView, the app will pass a boolean value to ContentView.
struct ContentView: View {
@ObservedObject var monster: MonsterObservable
var body: some View {
GeometryReader { geo in
ZStack {
HStack(spacing: 0.0) {
RightView(showMe: $monster.showDialog)
.frame(width: geo.size.width, height: geo.size.height)
}
ShowDialogView(isShowing: $monster.showDialog) {
}
.frame(width: 500, height: 600, alignment: .center)
.cornerRadius(10.0)
}
}
}
}
struct RightView: View {
@Binding var showMe: Bool
var body: some View {
ZStack {
Color.red
Button {
showMe = true
} label: {
Text("Tap me")
.font(.largeTitle)
}
}
}
}
class MonsterObservable: ObservableObject {
@Published var showDialog = false
}
struct ShowDialogView<Content: View>: View {
@Binding var isShowing: Bool
@ViewBuilder let content: () -> Content
var body: some View {
Group {
if isShowing {
ZStack {
Color.brown
VStack {
Spacer()
Button {
isShowing = false
} label: {
Text("Close me")
.font(.largeTitle)
}.padding([.top, .bottom], 100.0)
}
}
}
}
}
}
So the code above works. If I tap the button over RightView, a small dialog (ShowDialogView) will appear. Currently, ContentView and RightView are bound. That's not exactly what I need. How can I pass a boolean value from RightView to ContentView without Binding where ContentView is the following?
struct ContentView: View {
@ObservedObject var monster: MonsterObservable
var body: some View {
GeometryReader { geo in
ZStack {
HStack(spacing: 0.0) {
RightView()
.frame(width: geo.size.width, height: geo.size.height)
}
ShowDialogView(isShowing: $monster.showDialog) {
}
.frame(width: 500, height: 600, alignment: .center)
.cornerRadius(10.0)
}
}
}
}
I guess I've solved a problem on my own again.
import SwiftUI
struct ContentView: View {
@StateObject var monster = MonsterObservable.shared
var body: some View {
GeometryReader { geo in
ZStack {
HStack(spacing: 0.0) {
RightView()
.frame(width: geo.size.width, height: geo.size.height)
}
ShowDialogView(isShowing: $monster.showDialog) {
}
.frame(width: 500, height: 600, alignment: .center)
.cornerRadius(10.0)
}
}
}
}
struct ShowDialogView<Content: View>: View {
@Binding var isShowing: Bool
@ViewBuilder let content: () -> Content
var body: some View {
Group {
if isShowing {
ZStack {
Color.brown
VStack {
Spacer()
Button {
isShowing = false
} label: {
Text("Close me")
.font(.largeTitle)
}.padding([.top, .bottom], 100.0)
}
}
}
}
}
}
class MonsterObservable: ObservableObject {
static let shared = MonsterObservable()
@Published var showDialog = false
}
class GameScore: ObservableObject {
static let shared = GameScore()
@Published var score = 0
}
struct RightView: View {
@ObservedObject var monster = MonsterObservable.shared
var body: some View {
ZStack {
Color.red
Button {
monster.showDialog = true
} label: {
Text("Change")
.font(.largeTitle)
}
}
}
}