iOS SwiftUI-3 Callback使用方式


Posted by John on 2021-01-13

1.簡易Callback使用方法
2.搭配ObservableObject使用callback

  1. 簡易Callback使用方法

     //當SubView按下按鈕時,SubView會回call,並打印 index 0
     struct MainView: View {
         var body: some View {
             SubView(callback: .constant({ index in
                 print("index \(index)")
             }))
         }
     }
     struct SubView: View {
         @Binding var callback: (Int) -> ()
         var body: some View {
             Button(action: {
                 callback(0)
             }, label: {
                 Text("click")
             })
         }
     }
    
  2. 搭配ObservableObject使用callback
    ```
    class MainDelegate: ObservableObject {

     var data = false {
         didSet {
             dataCallback(data)
         }
     }
     var dataCallback: (Bool) -> () = {_ in}
     func setDataCallback(callback: @escaping (Bool) -> ()) {
         dataCallback = callback
     }
    

    }

struct MainView: View {
    @State var opacity: Double = 1
    @State var animation = false
    @ObservedObject var delegate: MainDelegate = MainDelegate()
    var body: some View {
        delegate.setDataCallback(callback: { flag in
            print("123")
        })
        return Button(action: {
            delegate.data.toggle()
        }, label: {
            Text("onClick")
        })
    }
}

```

更新於2021/01/12,後續有新的會再更新


##iOS #swift #SwiftUI #XCode #軟體語言 #程式設計







Related Posts

MTR04_0624

MTR04_0624

MTR04_0622

MTR04_0622

安裝 Spring Boot - spring boot initializr

安裝 Spring Boot - spring boot initializr


Comments