gpt4 book ai didi

swiftui - @ViewBuilder 在属性上与 init 中,存储闭包或结果值

转载 作者:行者123 更新时间:2023-12-03 08:02:11 25 4
gpt4 key购买 nike

有什么区别:

属性上的@ViewBuilder

struct SomeView<Content:View>: View {
@ViewBuilder var content: () -> Content
}

init中,存储闭包

struct SomeView2<Content:View>: View {
var content: () -> Content

init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
}

init中,存储结果值

struct SomeView3<Content:View>: View {
var content: Content

init(@ViewBuilder content: () -> Content) {
self.content = content()
}
}

所有解决方案似乎都有效。那么为什么人们会选择其中一种而不是另一种呢?

最佳答案

有人在今年的休息室询问,一位 Apple 工程师建议存储结果值。

Q: But, what’s the recommended way to use a @ViewBuilder for customcomponents: calling it right away in the init() and storing the view,or calling it later inside the body and storing the view builderitself?

A: We’d generally recommend resolving it right away andstoring the view

https://onmyway133.com/posts/wwdc-swiftui-lounge/#use-viewbuillder

例如这个版本

struct SomeView3<Content:View>: View {
let content: Content

init(@ViewBuilder content: () -> Content) {
self.content = content()
}
}

关于swiftui - @ViewBuilder 在属性上与 init 中,存储闭包或结果值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73729173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com