1

I have a barcode scanner that is using Vision, and it works great. How do I get the camera to play nicely with my VStack? Currently when I add the cameraView, the cameraView doesn't play nicely with the VStack, meaning it gets added as AVCaptureVideoPreviewLayer frame that I have to use to display the camera.

How can I make this work with the VStack so it's easier modified?

struct BarcodeScannerView: View {
    
    var pitchDegrees: CGFloat
    
    var cameraView = CameraView()
    
    var body: some View {
        
        VStack(spacing: 20) {
        
            Rectangle()
                .frame(width: 40, height: 5)
                .cornerRadius(3)


            Text("Barcode Scanner")
                .multilineTextAlignment(.center)
                .font(.body)
            
            Spacer()
            
            cameraView
                
            Spacer()
            
            Button(action: {
                print("Scan")
            }, label: {
                Text("Scan")
            })
            
            .frame(width: 200, height: 44)
            .background(Color.black)
            .foregroundColor(Color.white)
            .clipShape(Rectangle())
       
        }//VStack
        .frame(maxWidth: .infinity)
        .frame(height: 300)
        .padding()
        .background(Color("Warm White"))
        .clipShape(Rectangle())
        .shadow(radius: 5)
        .padding(.all, 5.0)
        
    }//body
}

CameraView

import Foundation
import SwiftUI

struct CameraView: UIViewControllerRepresentable {
    
    typealias UIViewControllerType = CameraViewController
    
    private let cameraViewController: CameraViewController
    
    init() {
        
        cameraViewController = CameraViewController()
        
    }//init
    
    func makeUIViewController(context: Context) -> CameraViewController {
        
        cameraViewController
        
    }//makeUIViewController
    
    func updateUIViewController(_ uiViewController: CameraViewController, context: Context) {

    }//updateUIViewController
        
}//struct

CameraViewController

class CameraViewController: UIViewController {

...

    func setupPreview() {
        
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        
        previewLayer.videoGravity = .resizeAspectFill
        previewLayer.connection?.videoOrientation = .portrait
        previewLayer.frame = CGRect(x: 0, y: 0, width: view.frame.width - 30, height: 200)
        previewLayer.cornerRadius = 15.0
        previewLayer.borderWidth = 1
        previewLayer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        previewLayer.shadowRadius = 5.0
        
        view.layer.addSublayer(previewLayer)
    
    }//setupPreview

...
}
Paul S.
  • 1,342
  • 4
  • 22
  • 43

0 Answers0