在Swift中执行3-4次后,DispatchQueue无法正常工作

6tqwzwtp  于 2022-11-21  发布在  Swift
关注(0)|答案(1)|浏览(148)

我有下面的代码来显示一个消息给用户,然后消失。一切工作正常的前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
            })
        })
    }
}

有没有人能看到我遗漏了什么,或者帮助弄清楚为什么它在多次执行后“停止”工作?

qmb5sa22

qmb5sa221#

有时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)
        
    }
}

相关问题