我想通過按下按鈕來驗證文本欄位的輸入。當用戶在文本欄位中輸入特定單詞(例如:Predator)時,它應該觸發 TextfieldVal 布林值,并在按下“發送”按鈕時將其設定為 true。除了捕食者之外,文本欄位中的任何其他內容都應該是假的。
現在我已經在互聯網上搜索了幾個小時,但仍然找不到我的答案。問了我環境中的一些人,但他們也幫不了我。你能把我送到正確的方向嗎?
這是我到目前為止想出的代碼。bool 有效,但我想念使其按預期作業的功能。因此驗證文本欄位并使特定單詞回傳 true,其他任何回傳 false。
@State var Textfield: String = ""
@State var Answer: String = ""
@State var ShowButton: Bool = false
@State var TextFieldVal: Bool = false
var body: some View {
VStack{
Text(Answer)
.frame(width: 400, height: 40, alignment: .center)
.font(.title)
.foregroundColor(Color.black)
TextField("Type here you answer...", text: $Textfield)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 250, height: 40, alignment: .center)
.background(Color.gray.opacity(0.5).cornerRadius(20))
.foregroundColor(.red)
.font(.headline)
Button {
if TextFieldVal == true {
ShowButton = true
Answer = String ("That is Correct!")
} else {
Answer = ("That is not correct")
}
} label: {
Text("Send")
.frame(width: 250, height: 40)
.background(Color(red: 0.272, green: 0.471, blue: 0.262))
.cornerRadius(20)
.foregroundColor(.white)
.font(.headline)
if ShowButton {
NavigationLink(
destination: Finish(),
label: {
Text("Next")
.frame(width: 120, height: 40)
.background(Color.red)
.cornerRadius(20)
.shadow(radius: 10)
.overlay(
Text("Verder")
.foregroundColor(.white)
)}
)}
}
}
}
}
uj5u.com熱心網友回復:
使用 onChange 修飾符。例子:
@State var Textfield: String = ""
@State var Answer: String = "Predator"
@State var ShowButton: Bool = false
@State var TextFieldVal: Bool = false
var body: some View {
VStack{
Text(Answer)
.frame(width: 400, height: 40, alignment: .center)
.font(.title)
.foregroundColor(Color.black)
TextField("Type here you answer...", text: $Textfield)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 250, height: 40, alignment: .center)
.background(Color.gray.opacity(0.5).cornerRadius(20))
.foregroundColor(.red)
.font(.headline)
Button {
if TextFieldVal == true {
ShowButton = true
Answer = "That is Correct!"
} else {
Answer = "That is not correct"
}
} label: {
Text("Send")
.frame(width: 250, height: 40)
.background(Color(red: 0.272, green: 0.471, blue: 0.262))
.cornerRadius(20)
.foregroundColor(.white)
.font(.headline)
if ShowButton {
NavigationLink(
destination: Example1(),
label: {
Text("Next")
.frame(width: 120, height: 40)
.background(Color.red)
.cornerRadius(20)
.shadow(radius: 10)
.overlay(
Text("Verder")
.foregroundColor(.white)
)}
)}
}
}
.onChange(of: Textfield) { _ in
if Textfield == "Predator" {
TextFieldVal = true
} else {
TextFieldVal = false
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312664.html
