繁体   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