0

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)
    }
}
shim
  • 9,289
  • 12
  • 69
  • 108
  • 1
    `UIImage(barcode: String)` isn’t a UIKit API. Is it a third party API? – Warren Burton Apr 26 '21 at 14:05
  • 1
    It is a third party API. This question has already been answered at [How can I generate a barcode from a string in Swift?](https://stackoverflow.com/questions/28542240/how-can-i-generate-a-barcode-from-a-string-in-swift). – Yrb Apr 26 '21 at 14:15
  • Have you tried putting `uiView.image = UIImage(barcode: barcode)` into the `makeUIView` function? – D. Mika Apr 26 '21 at 14:40

1 Answers1

1

you need to return a fully initialised view in makeUIView.

From the docs:

Creates the view object and configures its initial 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.

D. Mika
  • 2,577
  • 1
  • 13
  • 29