[英]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.