那是我一直在嘗試使按鈕像切換按鈕一樣的按鈕代碼,并在切換到“正在運行”時運行回圈并在按鈕回傳到“開始”時退出回圈...
@State private var buttonLabel = "開始"
Button(buttonLabel) {
if buttonLabel == "Running" {
buttonLabel = "Start"
} else {
buttonLabel = "Running"
}
while buttonLabel == "Running" {
print("running")
}
}
我什至嘗試在 while 陳述句的代碼部分的 print 陳述句下添加...
if buttonLabel != "Running {
break
}
當它在沒有while陳述句的情況下運行時......按鈕將開始顯示“開始”,按下時變為“正在運行”,再次按下時回傳“開始”。但是,當添加 while 回圈代碼時,當程式運行時......當您點擊“開始”時,文本會變暗并且不顯示“正在運行”,并且無法按下按鈕將其轉回“開始” " 或退出回圈。
uj5u.com熱心網友回復:
那是因為您讓 SwfiftUI 主執行緒忙于處理while. 如果您task想在while.
struct ButtonProblem: View {
@State var buttonLabel = "Start"
var body: some View {
Button(buttonLabel) {
if buttonLabel == "Running" {
buttonLabel = "Start"
} else {
buttonLabel = "Running"
}
Task.detached {
while buttonLabel == "Running" {
print("running")
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451154.html
上一篇:如何制作一個來回更改文本的功能
下一篇:點擊按鈕檢查單選或點擊單選
