简体   繁体   English

SwiftUI 条码不显示

[英]SwiftUI barcode does not show

I need to create a barcode based on existing text.I found many solutions to this problem, but none worked, instead of a barcode I saw just a white rectangle.我需要根据现有文本创建一个条形码。我找到了很多解决这个问题的方法,但没有一个有效,而不是条形码,我看到的只是一个白色矩形。 Here is non-working code, but maybe it will help you to find solution这是非工作代码,但也许它会帮助您找到解决方案

struct TestBarCodeView: View {
    var body: some View {
        VStack {
            BarCodeView(barcode: "1234567890")
                .scaledToFit()
                .padding().border(Color.red)
        }
    }
}

struct BarCodeView: UIViewRepresentable {
    let barcode: String
    func makeUIView(context: Context) -> UIImageView {
        UIImageView()
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
        uiView.image = UIImage(barcode: barcode)
    }
}

you need to return a fully initialised view in makeUIView .您需要在makeUIView返回一个完全初始化的视图。

From the docs:从文档:

Creates the view object and configures its initial state.创建视图 object 并配置其初始 state。

The following code works for me:以下代码适用于我:

struct BarCodeView: UIViewRepresentable {
    let barcode: String
    func makeUIView(context: Context) -> UIImageView {
        let imageView = UIImageView()
        imageView.image = UIImage(barcode: barcode)
        return imageView
    }

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

The updateUIView function does nothing, since the barcode property does not change. updateUIView function 什么都不做,因为条形码属性没有改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM