swift - 按下键盘后面的按钮时应用程序崩溃

标签 swift xcode swiftui

只要按下键盘后面的按钮,我正在创建的应用程序就会崩溃。

我有以下观点:

struct LoginSheetView: View {
 // Variables Here
    var body: some View {
        SwiftyHUDView(isShowing: self.$isLoading) {
            VStack{
                Text("Login")
                    .font(.largeTitle)
                    .fontWeight(.semibold)
                    .padding(.bottom, 20)
                TextField("Username", text: self.$username)
                    .padding(.bottom, 20)
                    .autocapitalization(.none)
                    .textContentType(UITextContentType.username)
                SecureField("Password", text: self.$password)
                    .padding(.bottom, 20)
                    .textContentType(UITextContentType.password)
                Button(action: {
                    self.isLoading = true
                    if(!self.username.isEmpty  && !self.password.isEmpty){
                        self.databaseCalls.login(username: self.username, password: self.password){ b in
                            self.isLoading = false
                            print("is loading: \(self.isLoading)")
                            if(b){
                                self.loginStatus = true
                                self.presentationMode.wrappedValue.dismiss()
                            }else{
                                self.showingAlert = true
                            }
                        }

                    }


                }){
                    Text("Login")
                        .frame(width: 220, height: 60)
                        .cornerRadius(15.0)
                }
            }
            .alert(isPresented: self.$showingAlert) {
                Alert(title: Text("Loging failed"), message: Text("Wrong username or password"), dismissButton: .default(Text("Got it!")))
            }
            .padding()

        }

    }
}

看起来像这样:

enter image description here

每当我在键盘打开时按下登录按钮时,我都会在文件AppDelegate中收到以下错误:

线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

如果我按键盘上的return,然后按Login按钮,则不会发生此错误。

关于导致错误的原因有什么想法吗?

注意: 我删除了一些代码(变量声明、填充、颜色等)以使其更容易理解

最佳答案

我添加了:

UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)

在按钮操作内,它已经解决了问题。有谁知道这是否是解决问题的正确方法?

关于swift - 按下键盘后面的按钮时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973022/

相关文章:

ios - 从 TableViewController 控制 Cell Item 的约束

swift - 通过按钮在新的 Web View 中打开 PDF 文件

iphone - 解析 JSON 中的新日期

ios - 如何在 SplitViewController 上显示 LoginViewController?

ios - 如何等待执行LocationService回调?

ios - 尽管图像很大,但 UIImageView 在 UICollectionViewCell 中显得很小

swift - 如何更改 NSSwitch 的色调颜色?

swift - 如何更改应用程序色调颜色(新的 SwiftUI 生命周期应用程序)?

swift - 在 Xcode 12 中使用 @main

swift - NSManagedObject更改不会触发objectWillChange