我试图在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错误
答案 0 :(得分:1)
在最近的Beta版本中,似乎TextField视图已更改。您应该可以使用以下方法创建一个:
struct MyView {
@State var myInput: String = ""
var body: some View {
TextField("placeholder text", text: $myInput)
}
}
答案 1 :(得分:0)
首先,您真的需要将这些视图合并到自定义视图中吗?如果是,则:
@State
和BindableObject
应该传递给视图中带有@Binding
关键字的属性不要使用某些本机类的相同名称
struct MyTextField : View {
@Binding var email: String
var body: some View {
VStack {
Text("Your email is \(email)!")
TextField($email, placeholder: Text("Enter your email"))
}
}
}
这样称呼
@State private var email: String = ""
var body: some View {
MyTextField(email: $email)
}
答案 2 :(得分:0)
@ RPatel99找到了答案。关闭并重新打开Xcode中的项目似乎已经解决了我的问题,现在我不再遇到Xcode中的错误。
@俄罗斯感谢您指出我应该更小心地使用文件名!
答案 3 :(得分:0)
在最近的Beta版Xcode中,TextField已更改。
@State var email: String = ""
var body: some View {
TextField("Email", text: $email, onEditingChanged: { (isChanges) in
// On Editing Changed
}) {
// On Commit
}
.padding(.leading, 13).padding(.trailing, 13).padding(.top, UIScreen.main.bounds.size.height / 2)
.textContentType(.emailAddress)
.textFieldStyle(RoundedBorderTextFieldStyle.init())
}
答案 4 :(得分:0)
类似于SearchView的TextField- XCODE 11.3
struct SearchBarV: View {
@State var text: String = ""
var onEditingChanged: (Bool) -> Void = { _ in }
var onCommit: () -> Void = { }
var body: some View {
GeometryReader { metrics in
TextField("placeholder", text: self.$text, onEditingChanged: self.onEditingChanged, onCommit: self.onCommit)
.background(Color.gray.opacity(0.1))
.padding(EdgeInsets(top: 0.0, leading: 16.0, bottom: 0, trailing: 16.0))
.frame(width: metrics.size.width, height: 50)
.keyboardType(.emailAddress)
}
}
}
struct SearchBarV_Previews : PreviewProvider {
static var previews: some View {
SearchBarV()
}
}