首页 > 解决方案 > SwiftUI TextField 简单示例不起作用

问题描述

我试图在 SwiftUI 中创建一个非常简单的 TextField,但我无法让它工作,我不明白我做错了什么。

Xcode 给了我一条错误消息,上面写着:

“无法推断复杂的闭包返回类型;添加显式类型以消除歧义。”

我不知道该怎么办。我在 StackOverflow 上找到了一些其他带有 SwiftUI 的 TextFields 代码示例,但一直收到相同的错误。

struct TextFieldExample : View {
    @State var email: String = "Enter email address"
    var body: some View {
        VStack {
            TextField($email)
            Text("Your email is \(email)!")
        }
    }
}
struct ButtonTextField : View {
    @State var text: String = ""

    var body: some View {
        HStack {
            TextField($text,
                      placeholder: Text("type something here..."))
            Button(action: {
                // Closure will be called once user taps your button
                print(self.$text)
            }) {
                Text("SEND")
            }
        }
    }
}

预期结果 = 工作 TextField 实际结果 = Xcode 中的错误

标签: swifttextfieldswiftui

解决方案


在最近的 beta 版本中,似乎 TextField 视图已更改。您应该能够使用以下内容创建一个:

struct MyView {
    @State var myInput: String = ""
    var body: some View {
      TextField("placeholder text", text: $myInput)
    }
}

推荐阅读