简体   繁体   English

更改状态属性值会更新 UI,但应用程序崩溃但 XCode 中没有任何错误报告 | 用户界面

[英]Changing state property value updates UI but app crashes without any error reporting in XCode | SwiftUI

I am using the below code for otp verification.我正在使用以下代码进行 otp 验证。 When the state property canSignUp is updated then the verified mobileNumber gets printed in the Text in the else block but as soon as it happens the app crashes and the xcode debugger doesn't show anything related to the crash.当状态属性canSignUp更新时,经过验证的 mobileNumber 会打印在 else 块的 Text 中,但一旦发生应用程序崩溃,xcode 调试器就不会显示与崩溃相关的任何内容。

           @State var mobileNumber = ""
           @State var canSignUp = false


           if !canSignUp {
               OTPView(onVerified: { mobile in
                    self.mobileNumber = mobile
                    self.canSignUp = true
                })
            } else {
                Text(mobileNumber)
            }

The same code doesn't produce any crash in the simulator while it does on a physical device.相同的代码在物理设备上不会在模拟器中产生任何崩溃。 I am using an iPhone 11 Pro Max我正在使用 iPhone 11 Pro Max

错误图像

This is what xcode looks like when the app crashes on the physical device当应用程序在物理设备上崩溃时 xcode 的样子

I can't figure out why, but the problem is with using if-else to show and hide the views.我不知道为什么,但问题在于使用 if-else 来显示和隐藏视图。 The crash was fixed when I put the views outside of if-else and used opacity to show and hide them.当我将视图放在 if-else 之外并使用不透明度来显示和隐藏它们时,崩溃得到了修复。 Furthermore, I put the views inside a ZStack so that the Text field doesn't get pushed down by the OTPView.此外,我将视图放在 ZStack 中,以便文本字段不会被 OTPView 压下。 Here's what it looks like.这是它的样子。

                   ZStack(alignment: .top) {
                       OTPView(onVerified: { mobile in
                            self.mobileNumber = mobile
                            self.canSignUp = true
                        }).opacity(!canSignUp ? 1 : 0)
                        
                        Text(mobileNumber).opacity(canSignUp ? 1 : 0)
                    }

While I am happy with this solution.虽然我对这个解决方案很满意。 I would still love to know why wouldn't it work if the visibility of the views are controlled with if-else我仍然很想知道如果使用 if-else 控制视图的可见性为什么它不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM