Can anyone tell me why the following code for publishing an anchor preference does not work:
Based on: https://swiftwithmajid.com/2020/03/18/anchor-preferences-in-swiftui/
enum MyPreferenceKeyType: Hashable {
case firstBounds
case secondBounds
}
struct MyPreferenceKey: PreferenceKey {
typealias Value = [MyPreferenceKeyType: Anchor<CGRect>]
static var defaultValue: Value { [:] }
static func reduce(value: inout Value, nextValue: () -> Value) {
value.merge(nextValue()) { $1 }
}
}
// Publish an anchor preference like this
.anchorPreference(key: MyPreferenceKey.self, value: .bounds) {
[MyPreferenceKeyType.firstBounds: $0]
}
In the above case the transform function is never called and the preference does not appear to be sent up the view hierarchy. However the following code works and the anchor preference is propagated up the view hierarchy:
struct MyPreferenceKey: PreferenceKey {
typealias Value = Anchor<CGRect>?
static var defaultValue: Value = nil
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
// Publish an anchor preference like this
.anchorPreference(key: MyPreferenceKey.self, value: .bounds) {
$0
}
Why is it that the transform closure is only called when there is nothing to transform?