Skladaniuk Max
Skladaniuk Max

Reputation: 13

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)
    }
}

Upvotes: 0

Views: 336

Answers (1)

D. Mika
D. Mika

Reputation: 2788

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.

Upvotes: 1

Related Questions