Assigning an ObservedState’s published value to a state

孤街浪徒 提交于 2020-06-28 06:41:26

问题


I have a state called time

@State var time = 0

and an ObservedObject called timerWrapper

@ObservedObject var timerWrapper = TimerWrapper()

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

and do this:

Text($time)

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

Text(self.timerWrapper.remainingSeconds)

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.


回答1:


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
   }


来源:https://stackoverflow.com/questions/62490734/assigning-an-observedstate-s-published-value-to-a-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!