简体   繁体   中英

Swift - didSet property not called from binding changes

My problem:

I want to call a function when my customView clicked

So I use @State variable to observe the click action from my custom view. But the problem is my value changed but didSet function not triggered

My code:

Main struct:

   @State var buttonClicked : Bool = false {
        didSet{
          needToCallMyFunction() // not triggered 
        }
    }

Custom struct:(for my customview)

@Binding var isClicked : Bool

someview
.onTapGesture(perform: {
            print("custom clicked")
            isClicked.toggle()
        })

Use instead in main view .onChange(of:) modifier, like

  SomeView()
    .onChange(of: buttonClicked) { _ in
       self.needToCallMyFunction()
    }

Update: variant for SwiftUI 1.0 / iOS 13+

import Combine   // needed to use Just

...

  SomeView()
    .onReceive(Just(buttonClicked)) { _ in
       self.needToCallMyFunction()
    }

Asperi solution working fine.

But it have one bug in lower versions. It called multiple times

I found another solution

SomeView(buttonClicked: 
             Binding(get: { self.buttonClicked },
                     set: { self.buttonClicked = $0
                               print("your action here ")
                }))
                       

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