简体   繁体   English

Swift - 绑定更改未调用 didSet 属性

[英]Swift - didSet property not called from binding changes

My problem:我的问题:

I want to call a function when my customView clicked当我的 customView 单击时,我想调用 function

So I use @State variable to observe the click action from my custom view.所以我使用@State 变量从我的自定义视图中观察点击动作。 But the problem is my value changed but didSet function not triggered但问题是我的值改变了但没有触发 didSet function

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在主视图中使用.onChange(of:)修饰符,例如

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

Update: variant for SwiftUI 1.0 / iOS 13+更新:SwiftUI 1.0 / iOS 13+ 的变体

import Combine   // needed to use Just

...

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

Asperi solution working fine. Asperi 解决方案工作正常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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