You don't need to call the function (using the global function is not a good idea.). Just use @State
and @Binding
Like this
struct FirstPage: View {
@State private var isVisible: Bool = false
var body: some View {
VStack{
NavigationView {
VStack{
Text("First Page")
.bold()
NavigationLink(destination: SecondPage(isVisible: $isVisible)) {
Image(systemName:"arrowshape.turn.up.right.circle")
}
}
}
if isVisible {
Image(systemName:"rhombus.fill")
.frame(width: 100, height: 100, alignment: .center)
}
}
}
}
struct SecondPage: View {
@Binding var isVisible: Bool
var body: some View {
VStack{
NavigationView {
VStack {
Text("Second Page")
.bold()
Button(action: {
isVisible = Bool.random()
}){
Text("Click here")
}
}
}
}
}
}
If you still need to use the global function then you need to create a static shared Observable class.
Here is an example:
Static shared class
class GlobalClass: ObservableObject {
static var shared = GlobalClass()
@Published var isVisibleVar: Bool = false
func isVisible() {
let result = Bool.random()
print("result", result)
isVisibleVar = result
}
}
Views
struct SecondPage: View {
var body: some View {
VStack{
NavigationView {
VStack {
Text("Second Page")
.bold()
Button(action: {
GlobalClass.shared.isVisible()
/**
Or you can use
GlobalClass.shared.isVisibleVar = Bool.random()
*/
}){
Text("Click here")
}
}
}
}
}
}
struct FirstPage: View {
@ObservedObject private var globalClass = GlobalClass.shared
var body: some View {
VStack{
NavigationView {
VStack{
Text("First Page")
.bold()
NavigationLink(destination: SecondPage()) {
Image(systemName:"arrowshape.turn.up.right.circle")
}
}
}
if globalClass.isVisibleVar {
Image(systemName:"rhombus.fill")
.frame(width: 100, height: 100, alignment: .center)
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…