【发布时间】:2019-07-22 06:51:33
【问题描述】:
正如标题所示,我正在尝试通过父视图 (P) 将数据从一个子视图 (A) 传递到另一个子视图 (B)。
父视图如下所示:
@State var rectFrame: CGRect = .zero
var body: some View {
childViewA(rectFrame: $rectFrame)
childViewB()
}
其中childViewA 获得childViewB 需要的CGRect。
childViewA 看起来像这样:
@Binding var rectFrame: CGRect
var body: some View {
// Very long code where rectFrame is obtained and printed to console correctly
}
如何将rectFrame 传递给childViewB?尽管在parentView 和childViewA 中都打印了正确的值,但到目前为止我尝试过的所有操作都会在childViewB 中返回CGRect.zero。
为了尝试将值传递给childViewB,我重写了parentView,如下所示:
@State var rectFrame: CGRect = .zero
var body: some View {
childViewA(rectFrame: $rectFrame)
childViewB(rectFrame: $rectFrame.value)
}
childViewB 具有以下结构:
var rectFrame: CGRect = CGRect.zero
var body: some View {
}
但这只是每次打印CGRect.zero。
我最近尝试了@ObjectBinding,但我一直在努力解决这个问题,所以如果有人能帮我解决这个具体的例子,我将不胜感激。
class SourceRectBindings: BindableObject {
let willChange = PassthroughSubject<Void, Never>()
var sourceRect: CGRect = .zero {
willSet {
willChange.send()
}
}
}
【问题讨论】:
-
你是如何设置框架的?它只能通过 a) PreferenceKey 或 b) DispatchQueue.main.async { ... } 设置,否则更改将不会被传播。
-
@arsenius PreferenceKey
-
也许检查你的实现?我一直在使用this 很多就好了。
.background(GeometryBinder(rect: self.$childFrame)). -
另外,这看起来有点可疑:
childViewB(rectFrame: $rectFrame.value)。为什么不只是self.rectFrame?