简体   繁体   中英

SwiftUI: Can't trigger Class function in View

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")
             }
        }
}

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")
             }
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM