簡體   English   中英

Swift - 綁定更改未調用 didSet 屬性

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

我的問題:

當我的 customView 單擊時,我想調用 function

所以我使用@State 變量從我的自定義視圖中觀察點擊動作。 但問題是我的值改變了但沒有觸發 didSet function

我的代碼:

主要結構:

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

自定義結構:(對於我的自定義視圖)

@Binding var isClicked : Bool

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

在主視圖中使用.onChange(of:)修飾符,例如

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

更新:SwiftUI 1.0 / iOS 13+ 的變體

import Combine   // needed to use Just

...

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

Asperi 解決方案工作正常。

但它在較低版本中有一個錯誤。 它調用了多次

我找到了另一個解決方案

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