【发布时间】:2021-12-30 10:51:27
【问题描述】:
我想通过子视图的函数调用来改变子视图的状态。但是视图没有更新。
struct MainView: View {
var subView: SubView = SubView()
var body: some View {
subView
Button("Button") {
subView.change()
}
}
}
struct SubView: View {
@State private var enabled = false
var body: some View {
if enabled {
Text("Some Label")
}
}
public func change() {
enabled.toggle()
}
}
使用@Binding 可以做到这一点,就像这里描述的那样:https://www.hackingwithswift.com/forums/swiftui/calling-functions-of-sub-views/1960
但我对这个解决方案不满意,因为我想完全提取视图。使用@Binding,我的主视图中仍然有一些子视图。
【问题讨论】: