Same array binded to two SwiftUI Views hangs-up App when object deleted

情到浓时终转凉″ 提交于 2021-01-28 11:18:42

问题


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

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