首页 > 解决方案 > 按下键盘后面的按钮时应用程序崩溃

问题描述

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

我有以下看法:

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()

        }

    }
}

看起来像这样:

在此处输入图像描述

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

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

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

关于导致错误的任何想法?

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

标签: swiftxcodeswiftui

解决方案


我已经添加:

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

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


推荐阅读