簡體   English   中英

SwiftUI:動作不會通過切換觸發

[英]SwiftUI: Action not triggering with toggle

我正在嘗試使用切換開關觸發操作。 在這種情況下,單擊切換按鈕后,控制台上不會顯示打印消息“值確實發生了變化”。

這是針對 macOS 10.15 應用程序的,.onChange 將不起作用。

struct ContentView: View {
    @State private var isToggle : Bool = false {
            didSet {
                print("value did change")
            }
    }

    var body: some View {
        Toggle(isOn: self.$isToggle){
                    Text("Toggle Label ")
         }
    }
}

在不應該(至少從來沒有以這種方式工作過),因為Toggle改變的不是狀態本身(通過直接分配給屬性)而是通過綁定包裝值......改為使用

@State private var isToggle : Bool = false

var body: some View {
    Toggle(isOn: self.$isToggle){
         Text("Toggle Label ")
     }
     .onChange(of: isToggle) { _ in
         print("value did change")   // << here !!
     }
}

我將無恥地竊取@Asperi 答案的第一部分,但第二部分是我的......

@State private var isToggle : Bool = false

var body: some View {
    Toggle(isOn: self.$isToggle.onUpdate({
        print("value did change")   // << here !!
    })){
        Text("Toggle Label ")
    }
}

extension Binding {
    
    /// Adds a modifier for this Binding that fires an action when a specific
    /// value changes.
    ///
    /// You can use `onUpdate` to trigger a side effect as the result of a
    /// `Binding` value changing.
    ///
    /// `onUpdate` is called on the main thread. Avoid performing long-running
    /// tasks on the main thread. If you need to perform a long-running task in
    /// response to `value` changing, you should dispatch to a background queue.
    ///
    /// The new value is NOT passed into the closure.
    ///
    ///     struct PlayerView: View {
    ///         var episode: Episode
    ///         @State private var playState: PlayState = .paused
    ///
    ///         var body: some View {
    ///             VStack {
    ///                 Text(episode.title)
    ///                 Text(episode.showTitle)
    ///                 PlayButton(playState: $playState.updated {
    ///                     model.playStateDidChange.update()
    ///                 })
    ///             }
    ///         }
    ///     }
    ///
    /// - Parameters:
    ///   - action: A closure to run when the value changes.
    ///
    /// - Returns: A new binding value.

    func onUpdate(_ action: @escaping () -> Void) -> Binding<Value> {
        Binding(get: {
            wrappedValue
        }, set: { newValue in
            wrappedValue = newValue
            action()
        })
    }
}

extension Binding {

    /// Adds a modifier for this Binding that fires an action when a specific
    /// value changes.
    ///
    /// You can use `updated` to trigger a side effect as the result of a
    /// `Binding` value changing.
    ///
    /// `updated` is called on the main thread. Avoid performing long-running
    /// tasks on the main thread. If you need to perform a long-running task in
    /// response to `value` changing, you should dispatch to a background queue.
    ///
    /// The new value is passed into the closure.
    ///
    ///     struct PlayerView: View {
    ///         var episode: Episode
    ///         @State private var playState: PlayState = .paused
    ///
    ///         var body: some View {
    ///             VStack {
    ///                 Text(episode.title)
    ///                 Text(episode.showTitle)
    ///                 PlayButton(playState: $playState.updated { newState in
    ///                     model.playStateDidChange(newState)
    ///                 })
    ///             }
    ///         }
    ///     }
    ///
    /// - Parameters:
    ///   - action: A closure to run when the value changes.
    ///
    /// - Returns: A new binding value.
    func updated(_ action: @escaping (_ value: Value) -> Void) -> Binding<Value> {
        Binding(get: {
            wrappedValue
        }, set: { newValue in
            wrappedValue = newValue
            action(newValue)
        })
    }
}

iOS 13 有兩個綁定擴展可以使用,watchOS 6 和 macOS 10。第一個.onUpdate()在綁定值更改時觸發,但不會讓您訪問舊值或新值。 它只是為了副作用。 我在上面使用這個只是因為print()不需要任何其他值。

如果您需要在閉包中使用 newValue,請使用.updated 它的工作原理與.onChange(of:)非常相似,只是它修改了 Binding 並且不允許您訪問舊值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM