SwiftUI 可选 @Binding 不会在第一次更改时更新其值

时间:2021-02-19 15:25:19

标签: swift swiftui

这是两天,我试图找出为什么可选绑定值从第一次开始没有改变的原因,如果它有值,除非我第二次进行更改(我进行了两次更改以响应绑定值),但是如果绑定值为零,然后我将其设置为从第一次开始就可以正常工作,这很奇怪,如果有人可以帮助我吗?

这是示例代码

    struct ParentView: View {
        
        @State var list: ListOfTasks?
        @State private var listGroup: ListOfTasks? = nil   // first value of binding
        
        var body: some View {
            // UI code here
            // Pass the value to "ChildView"
            NavigationLink(
                destination: ChildView(sublistGroup: $listGroup)) {
                // UI code here
            }
            .onAppear {
                // Set the binding value if we have it or its still nil
                if let editList = list {
                    listGroup = editList.origin
                }
            }
        }
    }
    
    struct ChildView: View {
        
        @Binding var listGroup: ListOfTasks?
        
        var body: some View {
            // UI code here
            .onTapGesture {
                // Here I try to change the listGroup value by give it some value or set it to nil, 
                // the problem is when I tap once it's not work unless I tap twice to respond the change.
                // listGroup = new value
                // listGroup = nil
            }
        }
    }

0 个答案:

没有答案