将ObservedState的发布值分配给一个州 [英] Assigning an ObservedState’s published value to a state

查看:105
本文介绍了将ObservedState的发布值分配给一个州的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做时间的状态

I have a state called time

@State var time = 0

和一个名为timerWrapper的ObservedObject

and an ObservedObject called timerWrapper

@ObservedObject var timerWrapper = TimerWrapper()

可以从子视图中更新

时间,如果我使用以下方法,我希望也可以使用timerWrapper(theObservedObject)更新它:

time can be updated from a child view and I want to be also able to update it using the timerWrapper (theObservedObject), if I use this:

self.time = self.timerWrapper.remainingSeconds

然后执行以下操作:

Text($time)

文本不会更新.仅当我这样做时才有效:

The text doesn’t update. It only works if I do this:

Text(self.timerWrapper.remainingSeconds)

我知道这是因为在发布剩余秒数时,它将重新加载用户界面. 但是我该如何解决呢?提醒我,有2个可能的源可以更新时间,这就是为什么我在viewbuilder中创建Text时不直接使用观察到的对象的原因.

I know that’s because when remainingSeconds is published it will reload the UI. But how can I get around this? Reminder I have 2 possible sources that can updated time, this is why I’m not using the observed object directly when creating the Text in the viewbuilder.

推荐答案

如果出于某种原因(无论出于何种原因)要更新视图模型发布的属性的本地状态,则可以使用此方法

If you want to update local state on view model published property (for whatever reason), here is a way to do this

Text(time)   // << not binding, just property
   .onReceive(timerWrapper.$remainingSeconds) { value in // listen for publisher $
      self.time = value
   }

这篇关于将ObservedState的发布值分配给一个州的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆