I am trying to improve a QR Scanner code since the current one is not respecting the .padding of the SwiftUI view neither the Spacer(). The QRScanner is a class that implements the UIViewRepresentable protocol and in the
func makeUIView(context: Context) -> UIView
method I setup the view:
let view = UIView(frame: UIScreen.main.bounds)//This seems to be the code that sets the size of the view.
However that size does not respect the SwiftUI padding and doesn't not change when rotating the iPhone.
This is the final part of the code in the makeUIView method
let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.frame = view.bounds //Suspicious code here
videoPreviewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(videoPreviewLayer)
DispatchQueue.global(qos: .userInitiated).async {
captureSession.startRunning()
}
return view
This is the parent SwiftUI view
VStack {
Text("QR scanner")
.font(.title)
if (errorMessage != "") {
Text(errorMessage)
}
if isShowingScanner {
QRScannerView(qrCode: $qrCode, isShowingScanner: $isShowingScanner, errorMessage: $errorMessage) ////Does not respect its position!
} else {
if (qrCode != "") {
Text("QR Scanned: \(qrCode)")
}
}
Spacer()//Does not respect this!
}
.padding()//Does not respect this either!
How do I change the size of the UIView as if it was a SwiftUI element?
I researched some part of the code and it seems the AVFoundation framework does not work with SwiftUI as it needs the UIViewRepresentable protocol to translate from UIKit to SwiftUI
I already tried with this question How to set UIView size to match parent without constraints programmatically
However it does not work as nothing is displayed after removing the UIScreen.main.bounds (also I found this code (the UIScreen.main.bounds) is deprecated) I've been unable to set the size of the UIView since it seems I do not have access in the QRScanner class to a Parent View Size property trying to use it as a @State variable to set the frame size. I even tried setting it as a state class variable obtained from the constructor and set in SwiftUI with no luck