gpt4 book ai didi

ios - 如何创建一个带有可选辅助 View 参数的 SwiftUI View ?

转载 作者:行者123 更新时间:2023-11-28 23:26:53 25 4
gpt4 key购买 nike

我正在尝试创建一个自定义 SwiftUI View ,它的行为类似于默认 View ,我可以在其中使用方法或可选的初始化参数向 View 添加额外内容。

SomeCustomView(title: "string argument") {
// some view
}

SomeCustomView(title: "hello") {
// some view
}.sideContent {
// another view
}

// This style is acceptable too
SomeCustomView(title: "hello", sideContent: { /* another view */ }) {
// some view
}

我如何修改这个 View 结构使其表现得像上面的例子一样?

struct SomeCustomView<Content>: View where Content: View {
let title: String
let content: Content

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

var body: some View {
VStack {
Text(title)
content
}
}
}

理想情况下,我有两个不同的主体"template",我可以根据是否调用了 sideContent 方法或设置了 sideContent 参数在它们之间切换。例如,

var body: some View {
VStack {
Text(title)
content
}
}

// or

var otherBody: some View {
HStack {
VStack {
Text(title)
content
}
sideContent
}
}

最佳答案

2021 年 11 月更新(适用于 Xcode 11.x、12.x 和 13.x)

经过一番思考和反复试验,我想通了。事后看来,这似乎有点明显。

struct SomeCustomView<Content>: View where Content: View {
let title: String
let content: Content

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

// returns a new View that includes the View defined in 'body'
func sideContent<SideContent: View>(@ViewBuilder side: @escaping () -> SideContent) -> some View {
HStack {
self // self is SomeCustomView
side()
}
}

var body: some View {
VStack {
Text(title)
content
}
}
}

无论有没有方法调用,它都可以工作。

SomeCustomView(title: "string argument") {
// some view
}

SomeCustomView(title: "hello") {
// some view
}.sideContent {
// another view
}

以前的代码有细微的错误:body 应该是 self

    func sideContent<SideContent: View>(@ViewBuilder side: @escaping () -> SideContent) -> some View {
HStack {
body // <--- subtle bug, updates to the main View are not propagated
side()
}
}

感谢 Jordan Smith 很久以前就指出了这一点。

关于ios - 如何创建一个带有可选辅助 View 参数的 SwiftUI View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384580/

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