我在下面有以下代碼向用戶顯示一條訊息然后消失。前 1 到 3 次嘗試一切正常,但超過此訊息視窗的任何內容都不會像之前的嘗試/要求那樣消失。
struct ContentView: View {
@State var showingNotice = false
var body: some View {
ZStack {
Button(action: {
self.showingNotice = true
}, label: {
Text("Show Notice")
})
if showingNotice {
FloatingNotice(showingNotice: $showingNotice)
}
}
.animation(.easeInOut(duration: 1))
}
}
struct FloatingNotice: View {
@Binding var showingNotice: Bool
var body: some View {
VStack (alignment: .center, spacing: 8) {
Image(systemName: "checkmark")
.foregroundColor(.white)
.font(.system(size: 48, weight: .regular))
.padding(EdgeInsets(top: 20, leading: 5, bottom: 5, trailing: 5))
Text("Review added")
.foregroundColor(.white)
.font(.callout)
.padding(EdgeInsets(top: 0, leading: 10, bottom: 5, trailing: 10))
}
.background(Color.snackbar.opacity(0.75))
.cornerRadius(5)
.transition(.scale)
.onAppear(perform: {
DispatchQueue.main.asyncAfter(deadline: .now() 2, execute: {
self.showingNotice = false
})
})
}
}
誰能看到我缺少的東西或幫助弄清楚為什么它在多次執行后“停止”作業?
uj5u.com熱心網友回復:
有時onAppear不會被呼叫,所以你self.showingNotice = false不會被呼叫。因此,您可以做一件事,將您的延遲塊移動到按鈕內單擊它,如下所示。
struct ContentView: View {
@State var showingNotice = false
var body: some View {
ZStack {
Button(action: {
self.showingNotice = true
DispatchQueue.main.asyncAfter(deadline: .now() 2, execute: {
self.showingNotice = false
})
}, label: {
Text("Show Notice")
})
if showingNotice {
FloatingNotice(showingNotice: $showingNotice)
}
}
.animation(.easeInOut(duration: 1))
}
}
struct FloatingNotice: View {
@Binding var showingNotice: Bool
var body: some View {
VStack (alignment: .center, spacing: 8) {
Image(systemName: "checkmark")
.foregroundColor(.white)
.font(.system(size: 48, weight: .regular))
.padding(EdgeInsets(top: 20, leading: 5, bottom: 5, trailing: 5))
Text("Review added")
.foregroundColor(.white)
.font(.callout)
.padding(EdgeInsets(top: 0, leading: 10, bottom: 5, trailing: 10))
}
.background(Color(.red))
.cornerRadius(5)
.transition(.scale)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/533045.html
標籤:迅速迅捷调度队列
上一篇:SwiftUI視圖API模式
下一篇:如何避免從模塊匯入功能
