如何解决SwiftUI - 文本字段返回键事件
首先,我很抱歉我的英语不完美。
我想根据通过文本字段中的返回键接收到的值的条件显示不同的图像。我搜索并尝试了几种方法,但找不到正确的方法。我在 SwiftUI 中找不到合适的返回键事件,所以我尝试了 onReceive。
Get-ChildItem -File -Exclude "*Confidential*" -Recurse |
Rename-Item -NewName { $_.BaseName + " - Confidential" + $_.Extension }
json.file
struct QuestionItemView: View {
@State private var question: Question?
@State private var answer = ""
var body: some View {
vstack(spacing: 30) {
GroupBox {
if let question = question {
Text(question.question)
.font(.largeTitle)
.fontWeight(.heavy)
.scaledToFit()
.frame(width: 300,height: 100)
.cornerRadius(12)
}
}
GroupBox {
TextField("Enter your answer",text: $answer)
.frame(width: 300)
.font(.title2)
.scaledToFit()
.cornerRadius(12)
.multilineTextAlignment(.center)
}
onReceive(answer.publisher) { _ in
if answer == question?.answer {
// Image(systemName: "circle")
print("o")
} else {
// Image(systemName: "multiply")
print("x")
}
}
} //: vstack
.frame(width: 240)
.background(RoundedRectangle(cornerRadius: 7.0).fill(Color.white))
.onAppear {
let questions: [Question] = Bundle.main.decode("questions.json")
question = questions.randomElement()
}
}
}
解决方法
你可以试试这样的:
To move/delete the file once the processing is completed
如果您使用的是旧系统,则可能需要这样做:
struct QuestionItemView: View {
@State private var question: Question?
@State private var answer = ""
@State private var imgType = ""
var body: some View {
VStack(spacing: 30) {
GroupBox {
if let question = question {
Text(question.question)
.font(.largeTitle)
.fontWeight(.heavy)
.scaledToFit()
.frame(width: 300,height: 100)
.cornerRadius(12)
}
}
GroupBox {
TextField("Enter your answer",text: $answer)
.frame(width: 300)
.font(.title2)
.scaledToFit()
.cornerRadius(12)
.multilineTextAlignment(.center)
.onSubmit { // <--- only on pressing the return key
// .onChange(of: answer) { _ in // <-- as you type
// .onReceive(answer.publisher) { _ in // <-- as you type
if answer == question?.answer {
imgType = "circle"
print("o")
} else {
imgType = "multiply"
print("x")
}
}
}
if imgType == "circle" {
Image(systemName: "circle")
} else {
Image(systemName: "multiply")
}
}
.frame(width: 240)
.background(RoundedRectangle(cornerRadius: 7.0).fill(Color.white))
.onAppear {
let questions: [Question] = Bundle.main.decode("questions.json")
question = questions.randomElement()
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。