问题
I try to build an app in MacOS SwiftUI, where two different subviews of main contentView shows different parts of Axis element:
struct ContentView: View {
@Binding var document: GlyphDesignerDocument
var body: some View {
HStack {
#warning("if AxesSlidersView is not commented, and Axis will be deleted — program explodes")
AxesSlidersView(axes: $document.axes)
AxesView(axes: $document.axes,
addRows: {document.axes.insert(Axis("z", bounds: 0...1000), at: $0)},
removeRows: {document.axes.remove(at: $0)},
addAxis: {document.axes.append(Axis("z", bounds: 0...1000))})
}
}
Subviews works great, everything updates in both ways, but application hangs-up when AxisView will delete one Axis from axes array.
All code is available at https://github.com/typoland/GlyphDesignerTest AxesView looks like this:
struct AxesView : View {
@Binding var axes: [Axis]
@State var selected: Int? = nil
var addRows: (_ at:Int) -> Void
var removeRows: (_ at: Int) -> Void
var addAxis: () -> Void
var body: some View {
VStack {
.... Shows Axes
}
}
}
struct AxisView: View {
@Binding var axis: Axis
var insert: () -> Void
var delete: () -> Void
@Binding var selected: Bool
var body: some View {
HStack {
.... Shows one Axis
}
}
}
struct AxesSlidersView: View {
@Binding var axes: [Axis]
var body: some View {
VStack {
.... Shows Axes
}
}
}
Is it SwiftUI problem? How to deal with this?
Github version, whole small app looks like this:
回答1:
I recall there were problems with direct binding with onDelete. Try with proxy binding in AxesSlidersView as below:
Slider(value: Binding(get: { axes[index].at }, set: {axes[index].at = $0}), in: axes[index].bounds)
.frame(idealWidth: metrics.frame(in: .global).width*0.6)
来源:https://stackoverflow.com/questions/64879906/same-array-binded-to-two-swiftui-views-hangs-up-app-when-object-deleted