带绑定的视图导致AnchorPreference在SwiftUI中返回nil

时间:2020-11-04 13:18:25

标签: swiftui

我正在使用SwiftUI中的AnchorPreferences。以下代码正确发送了首选项:

struct BoundsPreferenceKey: PreferenceKey {
    typealias Value = Anchor<CGRect>?

    static var defaultValue: Value = nil

    static func reduce(
        value: inout Value,
        nextValue: () -> Value
    ) {
        value = nextValue()
    }
}

struct ExampleView: View {
    
    @State var text = "Hello World"
    
    var settings = ["Option 1","Option 2"]
    @State var mapChoioce = 0
    
    var body: some View {
        VStack {
            Text(text)
                .anchorPreference(key: BoundsPreferenceKey.self,value: .bounds) { $0 }
        }
   
        .overlayPreferenceValue(BoundsPreferenceKey.self) { preferences in

            GeometryReader { geometry -> AnyView? in
                
                print("Preference")
                print(preferences)
                
                return preferences.map {
                    AnyView( Rectangle()
                        .stroke()
                        .frame(
                            width: geometry[$0].width,
                            height: geometry[$0].height
                        )
                        .offset(
                            x: geometry[$0].minX,
                            y: geometry[$0].minY
                        )
                    )
                }
            }
        }
    }
}

但是,如果我将Picker添加到混合中,由于某些非常奇怪的原因,anchorPreference会停止工作并返回nil。我也用TextField进行了测试,并且发生了相同的问题。似乎,任何消耗绑定的值都可能触发状态更改的值会使首选项返回nil。为什么会这样呢?如果我使用其他任何视图(例如Text),则一切正常。

struct ExampleView: View {
    
    @State var text = "Hello World"
    
    var settings = ["Option 1","Option 2"]
    @State var mapChoioce = 0
    
    var body: some View {
        VStack {
            Text(text)
                .anchorPreference(key: BoundsPreferenceKey.self,value: .bounds) { $0 }
            
            Picker("Options", selection: $mapChoioce) {
                ForEach(0 ..< settings.count) { index in
                    Text(self.settings[index])
                }
            }
            .pickerStyle(SegmentedPickerStyle())
        }
   
        .overlayPreferenceValue(BoundsPreferenceKey.self) { preferences in

            GeometryReader { geometry -> AnyView? in
                
                print("Preference")
                print(preferences)
                
                return preferences.map {
                    AnyView( Rectangle()
                        .stroke()
                        .frame(
                            width: geometry[$0].width,
                            height: geometry[$0].height
                        )
                        .offset(
                            x: geometry[$0].minX,
                            y: geometry[$0].minY
                        )
                    )
                }
            }
        }
    }
}

0 个答案:

没有答案