我对ButtonStyle的职称有问题。 启动 缩略语
我的法典如下:
struct TestPreferenceKey: PreferenceKey {
static var defaultValue: Int = 0
static func reduce(value: inout Int, nextValue: () -> Int) {
print("reduce value:", value)
print("reduce nextValue:", nextValue())
value = nextValue()
}
}
struct TestButtonStyle: ButtonStyle {
enum `Type` {
case a
case b
}
let type: `Type`
func makeBody(configuration: Configuration) -> some View {
switch type {
case .a:
configuration.label
case .b:
configuration.label
}
}
}
struct ButtonView: View {
var body: some View {
Button {
} label: {
Text("Button")
}
.buttonStyle(TestButtonStyle(type: .a))
}
}
struct ContentView: View {
var body: some View {
VStack {
ButtonView()
ButtonView()
}
.onPreferenceChange(TestPreferenceKey.self) { value in
print("value:", value)
}
}
}
我有以下的正文:
reduce value: 0
reduce nextValue: 0
value: 0
As I understand how PreferenceKey
works, I should have nothing printed out.
And it works so, if I call different function from ButtonStyle s makeBody
:
struct TestButtonStyle: ButtonStyle {
enum `Type` {
case a
case b
}
let type: `Type`
func makeBody(configuration: Configuration) -> some View {
switcher(configuration: configuration)
}
func switcher(configuration: Configuration) -> some View {
switch type {
case .a:
configuration.label
case .b:
configuration.label
}
}
}
Now, I have nothing printed out.
But, if I add @ViewBuilder
wrapper to switcher
function, I have printed out again:
...
@ViewBuilder
func switcher(configuration: Configuration) -> some View {
switch type {
case .a:
configuration.label
case .b:
configuration.label
}
}
reduce value: 0
reduce nextValue: 0
value: 0
Is it expected behavior with ViewBuilder
? Or is it a bug?
Is it always necessary to do such a traversal with an additional function?
如果有人知道答案的话,那将非常感激! 我也要感谢有关这个专题的有益联系!
UDP:
If I add .preference for one of Views, I get a wrong result of TestPreferenceKey value:
...
var body: some View {
VStack {
ButtonView()
.preference(
key: TestPreferenceKey.self,
value: 3
)
ButtonView()
}
.onPreferenceChange(TestPreferenceKey.self) { value in
print("value:", value)
}
}
结果:
reduce value: 3
reduce nextValue: 0
value: 0
Although the TestPreferenceKey value should be 3.
Of course, without @ViewBuilder
on switcher
TestPreferenceKey value is right - 3
印刷:
value: 3