我需要在扫描二维码时显示警报。如果扫描到正确的二维码,则需要显示“正确”警报,否则显示“不正确”。
以下是我尝试使用的代码。
免责声明 - 我不是 SwiftUI 方面的专家,但已经编码了很多年,并且在 SwiftUI 上使用了大约一年。我在理解 SwiftUI 方面可能还存在一些差距,我正在努力消除这些差距。
@Published var showingAlert = false
Button(action: {
showCameraForQR = true
}, label: {
Image ("QRCodeIcon")
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(Color.gray.opacity(0.5))
}).frame(width: 30, height: 30, alignment: .center)
.padding(.top,5)
.padding(.bottom,15)
.padding(.leading,5)
.padding(.trailing,5)
.sheet(isPresented: $showCameraForQR) {
CodeScannerView(codeTypes: [.qr], completion: handleScan)
}
.alert(isPresented: $showingAlert) {
Alert(title: Text(titleOfAlert))
}
func handleScan(result: Result<ScanResult, ScanError>) {
showCameraForQR = false
// Code to set the title.
titleOfAlert = "Correct"
// Trigger showing of alert now
showingAlert = true
}
当我执行此代码时,在相机打开并扫描二维码后,记录器中会看到以下日志,但没有警报消息:
Attempt to present <SwiftUI.PlatformAlertController: 0x104808e00> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x102018800> (from <_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x1021dae00>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x1022c7000>.
我相信,在调用警报之前,工作表不会关闭。那么,如何在调用警报之前关闭工作表?
注意,我使用的是 CodeScanner 2.3.3。
您可以尝试这种方法,当您设置
showingAlert = true
时
忽略 .sheet
,而不是将其设置在您的 func handleScan
中。
例如使用:
.sheet(isPresented: $showCameraForQR, onDismiss: {showingAlert = true}) {...}