警报按钮的.default成员的没有上下文类型错误

时间:2019-11-17 06:29:57

标签: swift swiftui

此示例代码显示单击按钮时代表警报的按钮。

struct LoginView: View {
    ...
    @State private var showAlert = false

    var body: some View {
        NavigationView {
            VStack {
                ...

                Button("Login") {
                    self.showAlert = true
                }
                .alert(isPresented: self.$showAlert) {
                    Alert(title: Text("Login error"), message: Text("detail message"), dismissButton: .default(Text("Ok")))  // this line report a error
                }
            }
            .navigationBarTitle("Login View")
        }
    }
}

但是,当我编译此代码时,Xcode会报告一条Reference to member 'default' cannot be resolved without a contextual type错误消息。我该如何解决此代码?

3 个答案:

答案 0 :(得分:1)

带有呈现代码的项目可以在iOS SimulatoriOS device中正常运行,没有任何错误。 Canvas Simulator也可以正常工作(我使用Xcode 11.2.1和iOS 13.2.2)。

enter image description here

尝试删除文件夹DerivedData中的所有已编译项目。

在Finder中,按 Cmd - Shift - G 并转到:

~/Library/Developer/Xcode/DerivedData/

清除此文件夹的内容后,再次构建您的项目,它必须能够按预期工作。

答案 1 :(得分:0)

我通过实验发现,由于另一条代码路径中的编译问题,Xcode提供了这种愚蠢的行为(它表明您有编译错误但没有到位,这是此错误的来源)。

下一个是我的解决方案:

1)评论内部所有内容

public var body: some View {
   . . . . . 
}

2)成功建立项目

3)按视图取消评论。取消注释后成功构建将帮助您找到真正的错误地方

例如,我在 sendRequest 函数上遇到了问题

Button(
        action: {

            self.sendRequest(requestUrl: self.requestUrl!, requestData: self.requestData!, requestMethod: RequestMethod.GET, handler: { rd, sa, am in
                                        self.responseData = rd
                                        self.showingAlert = sa ?? false
                                        self.alertMessage = am
                                    })

        },
        label: { Text("Get Data") }
       )
       .alert(isPresented: $showingAlert) {
           Alert(title: Text("Important!"), message: Text("\(alertMessage!)"), dismissButton: .default(Text("Got it!")))
       }
       .buttonStyle()

和Xcode在“警告...”行上显示“没有警报按钮.default成员的上下文类型错误”错误

答案 2 :(得分:0)

我收到此错误消息是因为括号未正确配对。您的代码有效,这些版本也有效:

.alert(isPresented: $showAlert) {
    Alert(title: Text("Title"),
          message: Text("An alert"),
          primaryButton: .default(Text("OK"), action: {
          }),
          secondaryButton: .cancel(Text("Cancel"), action: {
          })
    )
}

或者这个:

.alert(isPresented: $showAlert) {
    Alert(title: Text("Title"),
          message: Text("An alert"),
          primaryButton: .default(Text("OK")) {
          },
          secondaryButton: .cancel(Text("Cancel"))
    )
}