簡體   English   中英

如何在 SwiftUI 中使用 ViewBuilder 在自定義視圖/組件上將內容限制為 Text()

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

我使用 SwiftUI 創建了一個自定義組件。 它類似於類似於文本字段的下拉列表,但是當您點擊它時,它會顯示一個包含選項列表的工作表。 這是選擇器的代碼:

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,並且它必須僅為 Text()。 有沒有辦法做到這一點?

提前致謝!

我想將視圖數量限制為 1,並且它必須僅為 Text()。 有沒有辦法做到這一點?

是的,您不需要為此目的使用泛型,您需要明確指定 Text 並且編譯器不允許任何其他內容,並且 Text 不是容器,因此始終只是一個容器。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM