簡體   English   中英

如何制作通用 UIViewRepresentable 結構?

[英]How can I make a generic UIViewRepresentable struct?

我想構建一個將 UI 類型作為輸入的結構,並在 SwiftUI 中顯示 UI,例如,我有 UILabel 和 UIButton 的向下代碼,我想制作一個通用的,讓我不必為每個 UI 制作單獨的結構來自 UIKit:

struct UILabelViewRepresentable: UIViewRepresentable {
    
    let configuration: (UILabel) -> ()
    
    func makeUIView(context: Context) -> UILabel {
       return UILabel()
    }
    
    func updateUIView(_ uiView: UILabel, context: Context) {
        configuration(uiView)
    }
}



struct UIButtonViewRepresentable: UIViewRepresentable {
    
    let configuration: (UIButton) -> ()
    
    func makeUIView(context: Context) -> UIButton {
       return UIButton()
    }
    
    func updateUIView(_ uiView: UIButton, context: Context) {
        configuration(uiView)
    }
}

這是我到目前為止所嘗試的:

struct GenericUIViewRepresentable<UIViewType: UIView>: UIViewRepresentable {
    
    let uiViewType: UIViewType
    let configuration: (UIViewType) -> ()
    
    func makeUIView(context: Context) -> UIViewType {
        return uiViewType
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
        configuration(uiView)
    }
}

當我想使用它時會出錯:

無法將“UILabel.Type”類型的值轉換為預期的參數類型“UIView”

所以我知道這個錯誤,我想讓我的代碼工作,它讓我可以自由地輸入我想要的所有 UIKit UI。

用例:

struct ContentView: View {
    
    var body: some View {
        
        GenericUIViewRepresentable(uiViewType: UILabel, configuration: { label in
            label.text = "Hello, World!"
        })

    }
    
}

您想傳入UIView類型,而不僅僅是UIView實例。 這意味着你想做UIViewType.Type而不是UIViewType

代碼:

struct GenericUIViewRepresentable<UIView: UIKit.UIView>: UIViewRepresentable {
    let uiViewType: UIView.Type
    let configuration: (UIView) -> ()

    func makeUIView(context: Context) -> UIView {
        uiViewType.init()
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        configuration(uiView)
    }
}

用法:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello world!")

            GenericUIViewRepresentable(uiViewType: UILabel.self) { label in
                label.text = "Other text!"
            }
        }
    }
}

swift.org上,您可以了解有關元類型的更多信息。

暫無
暫無

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

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