如何在 SwiftUI 中使用 ViewBuilder 在自定义 view/component 上将内容限制为 Text()

How to restrict content to Text() on custom view/component using ViewBuilder in SwiftUI

我使用 SwiftUI 创建了一个自定义组件。它类似于类似于文本字段的下拉列表,但当您点击它时,它将显示包含选项列表的 sheet。这是选择器的代码:

struct PickerWidget<Content: View>: View{
var action: () -> Void
private let content: () -> Content

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

var body: some View {
    Button(action: {
        self.action()
    })
    {
        HStack{
            content()
                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                .foregroundColor(Color.black)
            Image(systemName: "chevron.down")
        }
        .padding()
        .overlay(
            RoundedRectangle(cornerRadius: 10)
                .stroke(Color.gray, lineWidth: 1)
        )
    }
    .padding()
}

}

下面是它在父视图中的使用方式:

        PickerWidget(action: { self.isSheetShown.toggle() }){
            Text("US Dollars (USD)")
        }
        .sheet(isPresented: $isSheetShown){
            CurrencyPickerView(isSheetShown: self.$isSheetShown)
        }

效果很好。但我想将视图数限制为 1,并且必须是 ONLY Text()。有办法吗?

提前致谢!

I would like to restrict the number of views to just 1 and it has to be ONLY Text(). Is there a way to do this?

是的,您不需要为此目的使用泛型,您需要明确指定 Text 并且编译器不允许任何其他内容,并且 Text 不是容器,因此始终只有一个。

struct PickerWidget: View {
   var action: () -> Void
   private let content: () -> Text

  init(action: @escaping () -> Void, @ViewBuilder content: @escaping () -> Text) {
     ...