gpt4 book ai didi

ios - 可选的@ViewBuilder 闭包

转载 作者:行者123 更新时间:2023-12-01 15:30:41 26 4
gpt4 key购买 nike

在 SwiftUI 中是否有可能有一个可选的 @ViewBuilder关闭?例如,假设我想开发一个自定义 View ,它需要两个 View 构建器闭包,如下所示:

import SwiftUI

struct TopAndBottomView<Content>: View where Content: View {
let topContent: () -> Content
let bottomContent: () -> Content

init(@ViewBuilder topContent: @escaping () -> Content, @ViewBuilder bottomContent: @escaping () -> Content) {
self.topContent = topContent
self.bottomContent = bottomContent
}

var body: some View {
VStack {
topContent()
Spacer()
bottomContent()
}
}
}

struct TopAndBottomView_Previews: PreviewProvider {
static var previews: some View {
TopAndBottomView(topContent: {
Text("TOP")
}, bottomContent: {
Text("BOTTOM")
})
}
}

但我希望底部 View 是可选的。我试过:
struct TopAndBottomView<Content>: View where Content: View {
let topContent: () -> Content
let bottomContent: (() -> Content)?

init(@ViewBuilder topContent: @escaping () -> Content, @ViewBuilder bottomContent: (() -> Content)? = nil) {
self.topContent = topContent
self.bottomContent = bottomContent
}

var body: some View {
VStack {
topContent()
Spacer()
if bottomContent != nil {
bottomContent!()
}
}
}
}

但我收到此错误:

Function builder attribute 'ViewBuilder' can only be applied to a parameter of function type.



谢谢。

最佳答案

考虑到buildIf ViewBuilder的特点以下方法允许保留 ViewBuilderinit (这是最好的)

经过测试并与 Xcode 11.2/iOS 13.2 一起使用

struct TopAndBottomView<Content>: View where Content: View {
let topContent: () -> Content
let bottomContent: () -> Content?

init(@ViewBuilder topContent: @escaping () -> Content,
@ViewBuilder bottomContent: @escaping () -> Content? = { nil }) {
self.topContent = topContent
self.bottomContent = bottomContent
}

var body: some View {
VStack {
topContent()
Spacer()
bottomContent()
}
}
}

所以就像这个一样
struct TopAndBottomView_Previews: PreviewProvider {
static var previews: some View {
TopAndBottomView(topContent: {
Text("TOP")
}, bottomContent: {
Text("BOTTOM")
})
}
}

和这个
struct TopAndBottomView_Previews: PreviewProvider {
static var previews: some View {
TopAndBottomView(topContent: {
Text("TOP")
})
}
}

关于ios - 可选的@ViewBuilder 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60687912/

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