如何在 SwiftUI 中为视图定义默认的空输入内容?

use*_*ser 2 swiftui

我有 CustomContentView(),我喜欢给它一个像 {} 这样的空内容作为默认值,在用例中我不必这样做,例如我对 Color 做了同样的事情!

更多信息:答案可以解决问题,无需使用 ViewBuilder,甚至无需将 CustomContentView 转换为功能,一切都可以,直到我们能够根据需要提供内容!

    struct ContentView: View {
    var body: some View {

        CustomContentView(content: { Text("hello") })

        CustomContentView(content: { })
        // I like this one: CustomContentView() How can I do this?
  
    }
 
}
Run Code Online (Sandbox Code Playgroud)
struct CustomContentView<Content: View>: View {
    
    let content: () -> Content
    let color: Color
    
    init( @ViewBuilder content: @escaping () -> Content, color: Color = Color.red) {
        
        self.content = content
        self.color = color
        
    }
    
    var body: some View {

        ZStack {
            
            Rectangle()
                .fill(color)
 
             content()

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

New*_*Dev 5

因为CustomContentView是 的泛型类型Content,并且您希望默认内容为空,所以您需要创建一个init限制为 的Content重载EmptyView

init(color: Color = .red) where Content == EmptyView {
   self.init(content: { EmptyView() }, color: color)
}
Run Code Online (Sandbox Code Playgroud)

用法如您所料:

CustomContentView()
// or
CustomContentView(color: .blue)
Run Code Online (Sandbox Code Playgroud)