Home > database >  SwiftUI: Can't trigger Class function in View
SwiftUI: Can't trigger Class function in View

Time:11-03

I want to trigger a function from a class with a button in my view, but nothing is happening when clicking on the button.

This is for a macOS 10.15 app

Class

class StatusBar: ObservableObject {
    func testing(){
          print("Hello World")
    }
}

View

struct ContentView: View {
   @State var stat: StatusBar?

    var body: some View {
          Button {
                 stat?.testing()
            } label: {
                Text("Testing")
             }
        }
}

CodePudding user response:

You've declared StatusBar as an Optional and there's no code shown giving it a value. If it's nil, nothing will happen when you call ?.testing() on it. If you give it a value, it will be called.

Secondly, since StatusBar is an ObservableObject, it should probably be @StateObject instead of @State.

class StatusBar: ObservableObject {
    func testing(){
          print("Hello World")
    }
}

struct ContentView: View {
   @StateObject var stat = StatusBar()

    var body: some View {
          Button {
                 stat.testing()
            } label: {
                Text("Testing")
             }
        }
}
  • Related