简体   繁体   English

使用 SwiftUI 启动 TextField 时出现 VStack 错误

[英]VStack error when I initiate a TextField using SwiftUI

There are no errors until I create this TextField .在我创建这个TextField之前没有错误。

Also, there are no errors if I create a TextField("Placeholder", text: .constant("")) like this.另外,如果我像这样创建一个TextField("Placeholder", text: .constant(""))也没有错误。

I am trying to use the data from the TextField which is of type Int.我正在尝试使用来自 Int 类型的 TextField 的数据。

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

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

The error is with the TextField and it actually:错误出在TextField ,它实际上是:

Cannot invoke initializer for type 'TextField<_>' with an argument list of type '(Binding)'无法使用类型为“(Binding)”的参数列表调用类型“TextField<_>”的初始值设定项

To fix that, You need to first provide a title and the label of the binding argument: text :要解决这个问题,您需要首先提供一个title和绑定参数的标签: text

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

And note that TextField can not accept a number as the binding argument alone!并注意TextField不能单独接受数字作为绑定参数! You must also provide a Formatter to make it working:您还必须提供一个Formatter以使其工作:

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

Also as I mentioned here , you should not trust Xcode error reasons, Specially when you are working with SwiftUI.同样正如我在这里提到的,你不应该相信 Xcode 错误的原因,特别是当你使用 SwiftUI 时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自定义 TextField 在 SwiftUI 代码中的 VStack 中不起作用 - Customized TextField not working in VStack in SwiftUI code 在 SwiftUI 中的 Scrollview(列表的替代方案)中使用 VStack 时的性能 - Performance when using a VStack inside a Scrollview (alternatives to List) in SwiftUI SwiftUI VStack中大文本和TextField之间的神秘间距 - SwiftUI mysterious spacing between large Text and TextField in VStack 使用 TextField 在 VStack 中隐藏其下方的 ScrollView - Using TextField hides the ScrollView beneath it in VStack 为什么我不能使用.cornerRadius()编辑VStack中的TextField? - Why cannot I edit TextField in VStack with a .cornerRadius()? SwiftUI animation 嵌套在 VStack 中失败 - SwiftUI animation fails when nested in VStack 使用 ViewModifiers 的 VStack 中的 SwiftUI 布局 - SwiftUI layout inside VStack using ViewModifiers 使用 swiftUI 文本字段和 WKWebView 文本字段时应用程序崩溃 - App crashes when using a swiftUI textfield and a WKWebView textfield SwiftUI:VStack中的VStack,标签被截断 - SwiftUI: VStack in VStack, labels are truncated 长按键盘时,TextField 显示 -[UIWindow endDisablingInterfaceAutorotationAnimated:] 错误 (SwiftUI) - TextField displays -[UIWindow endDisablingInterfaceAutorotationAnimated:] error when keyboard is long pressed (SwiftUI)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM