使用 SwiftUI 启动 TextField 时出现 VStack 错误
VStack error when I initiate a TextField using SwiftUI
在我创建这个 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)
}
}
}
错误与 TextField
有关,实际上是:
Cannot invoke initializer for type 'TextField<_>' with an argument list of type '(Binding)'
要解决这个问题,您需要先提供一个 title
和绑定参数的标签:text
:
TextField("This can be an empty string", text: $answerString)
请注意 TextField
不能单独接受数字作为绑定参数!您还必须提供 Formatter
才能使其正常工作:
TextField("", value: $answer, formatter: NumberFormatter())
另外正如我提到的 ,你不应该相信 Xcode 错误原因,特别是当你使用 SwiftUI 时。
在我创建这个 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)
}
}
}
错误与 TextField
有关,实际上是:
Cannot invoke initializer for type 'TextField<_>' with an argument list of type '(Binding)'
要解决这个问题,您需要先提供一个 title
和绑定参数的标签:text
:
TextField("This can be an empty string", text: $answerString)
请注意 TextField
不能单独接受数字作为绑定参数!您还必须提供 Formatter
才能使其正常工作:
TextField("", value: $answer, formatter: NumberFormatter())
另外正如我提到的