我正在制作一个基于 Section() 的自定义 SwiftUI 视图。我的基本代码如下所示,其工作原理如下:
struct SettingsSection<Header: View, Content: View>: View {
var header: () -> Header
var content: () -> Content
init(@ViewBuilder header: @escaping () -> Header, @ViewBuilder content: @escaping () -> Content)
{
self.header = header
self.content = content
}
var body: some View {
Section(content: {
content()
}, header: {
header()
})
}
}
但是我想添加一个更简单的 init,它只接受字符串作为标头。我尝试执行以下操作:
init(_ headerStr: String, @ViewBuilder content: @escaping () -> Content) {
self.init(header: {
Text(headerStr)
}, content: content )
}
但是如果像这样使用 SettingsSection,我会收到错误“无法推断通用参数‘Header’”,这正是我想要的:
SettingsSection("Actions") {
// ... content of the section
}
我可以理解使用这个新的 init() 没有指定 Header 类型,但肯定有一种方法可以创建这种简化的构造函数......我是对的吗?
你只需要用's
init
标记Header
Type