Why isn't onPreferenceChange being called if it's inside a ScrollView in SwiftUI?

前端 未结 5 2039
逝去的感伤
逝去的感伤 2021-01-02 02:57

I\'ve been seeing some strange behavior for preference keys with ScrollView. If I put the onPreferenceChange inside the ScrollView it won\'t be cal

5条回答
  •  离开以前
    2021-01-02 03:03

    You may only read it in superView, but you can change it with transformPreference after you set it .

    struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack{
            Text("Hello")
                .preference(key: WidthPreferenceKey.self, value: 20)
            }.transformPreference(WidthPreferenceKey.self, {
            $0 = 30})
        }.onPreferenceChange(WidthPreferenceKey.self) {
            print($0)
        }
    }
    }
    

    The last value is 30 now. Hope it is what you want.

    You can read from other layer:

      ScrollView {
    
            Text("Hello").preference(key: WidthPreferenceKey.self, value: CGFloat(40.0))
                .backgroundPreferenceValue(WidthPreferenceKey.self) { x -> Color in
                   print(x)
                    return Color.clear
            }
    
        }
    

提交回复
热议问题