【问题标题】:VStack error when I initiate a TextField using SwiftUI使用 SwiftUI 启动 TextField 时出现 VStack 错误
【发布时间】:2019-12-01 17:20:57
【问题描述】:

在我创建此 TextField 之前没有错误。

另外,如果我像这样创建TextField("Placeholder", text: .constant("")),也不会出现错误。

我正在尝试使用 Int 类型的 TextField 中的数据。

struct ContentView: View {
    @State private var answer: Int = 0

    var body: some View {
        VStack(alignment: .center) {
            Text("some text")
            Spacer()
            TextField($answer)
        }
    }
}

【问题讨论】:

    标签: swift textfield swiftui


    【解决方案1】:

    错误在于TextField,实际上是:

    无法使用类型为“(绑定)”的参数列表调用类型“TextField<_>”的初始化程序

    要解决这个问题,您需要首先提供title 和绑定参数的标签:text

    TextField("This can be an empty string", text: $answerString)
    

    注意TextField 不能单独接受一个数字作为绑定参数!您还必须提供Formatter 才能使其正常工作:

    TextField("", value: $answer, formatter: NumberFormatter())
    

    正如我提到的here,你不应该相信 Xcode 错误的原因,特别是当你使用 SwiftUI 时。

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2021-08-04
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2019-08-06
      相关资源
      最近更新 更多