func anchorPreference<A, K>(key _: K.Type = K.self, value: Anchor<A>.Source, transform: @escaping (Anchor<A>) -> K.Value) -> some View where K : PreferenceKey
func overlayPreferenceValue<Key, T>(_ key: Key.Type = Key.self, @ViewBuilder _ transform: @escaping (Key.Value) -> T) -> some View where Key : PreferenceKey, T : View
See the key
parameter has this default value. But I cannot figure out how to write code to leverage this defalult. All the examples define a separate struct Xxx: PreferenceKey
and pass Xxx.self
to these call. I thought well, maybe the key
default assume the View
itself implements PreferenceKey
, doing so I still cannot remove passing in the key
parameter:
// Example from https://swiftwithmajid.com/2020/03/18/anchor-preferences-in-swiftui/
import SwiftUI
//fileprivate struct BoundsPreferenceKey: PreferenceKey {
// typealias Value = Anchor<CGRect>?
//
// static var defaultValue: Value = nil
//
// static func reduce(
// value: inout Value,
// nextValue: () -> Value
// ) {
// value = nextValue()
// }
//}
struct AnchorPreferencesExample: PreferenceKey, View {
typealias Value = Anchor<CGRect>?
static var defaultValue: Value = nil
static func reduce(
value: inout Value,
nextValue: () -> Value
) {
value = nextValue()
}
var body: some View {
ZStack {
Color.yellow
Text("Hello World !!!\nYou okay?\nOr not?")
.multilineTextAlignment(.center)
.padding()
.anchorPreference(
key: AnchorPreferencesExample.self, // <<<<< but still cannot remove this param
value: .bounds
) { $0 }
}
// VVV--- and still cannot remove this
.overlayPreferenceValue(AnchorPreferencesExample.self) { preferences in
GeometryReader { geometry in
preferences.map {
Rectangle()
.stroke()
.frame(
width: geometry[$0].width,
height: geometry[$0].height
)
.offset(
x: geometry[$0].minX,
y: geometry[$0].minY
)
}
}
}
}
}
struct AnchorPreferencesExample_Previews: PreviewProvider {
static var previews: some View {
AnchorPreferencesExample()
}
}
So how to make this example make use of the key
default as the api intend?